Swagger配置
1.简介
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务(http s://swagger.io/)。 它的主要作用是:
- 使得前后端分离开发更加方便,有利于团队协作
- 接口的文档在线自动生成,降低后端开发人员编写接口文档的负担
- 功能测试 Spring已经将Swagger纳入自身的标准,建立了Spring-swagger项目,现在叫Springfox。通过在 项目中引入Springfox ,即可非常简单快捷的使用Swagger。
2.Springboot集成
1、引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
2、配置文件中开启Swagger
# 开启swagger
swagger.enable=true
3、创建Swagger配置类
@Configuration
@ConditionalOnProperty(prefix = "swagger",value = {"enable"},havingValue = "true")
@EnableSwagger2 //开启swagger注解支持
public class SwaggerConfiguration {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("扫描的包路径"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo buildApiInfo() {
Contact contact = new Contact("黑马程序员","","");
return new ApiInfoBuilder()
.title("万信金融P2P平台-用户服务API文档")
.description("包含用户服务api")
.contact(contact)
.version("1.0.0").build();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ssCkdL9i-1607152643469)(C:\Users\acer\AppData\Roaming\Typora\typora-user-images\image-20201022164633381.png)]
4、常用注解
注解 | 解释 |
---|---|
@Api | 修饰整个类,描述Controller的作用 |
@ApiOperation | 描述一个类的一个方法,或者说一个接 口 |
@ApiParam | 单个参数的描述信息 |
@ApiResponse | HTTP响应其中1个描述 |
@ApiResponses | HTTP响应整体描述 |
@Apilgnore | 使用该注解忽略这个API |
@ApiError | 发生错误返回的信息 |
@ApiModelProperty | 接收参数时,描述对象的一个字段 |
@ApiModel | 用对象来接收参数 |
@ApilmplicitParams | 多个请求参数的描述信息 |
@ApiImplicitParam↓ | 一个请求参数用对象 |
@RestController
@Api(value = "用户服务的Controller", tags = "Consumer", description = "用户服务API")
public class ConsumerController {
@ApiOperation("测试hello")
@GetMapping(path = "/hello")
public String hello(){
return "hello";
}
@ApiOperation("测试hi")
@PostMapping(path="/hi")
@ApiImplicitParam(name="name",value = "姓名",required = true,dataType = "String")
public String hi(String name){
return "hi,"+name;
}
}
启动不了 :配置WebMvcConfigurer
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 重新指定静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
// 解决 SWAGGER2 404报错
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
}
}