Swagger详解
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
在前后端分离开发的过程中前端和后端需要进行api对接进行交互就需要一个api规范文档方便前后端的交互但api文档不能根据代码的变化发生实时动态的改变这样后端修改了接口前端不能及时获取最新的接口导致调用出错需要手动维护api文档加大了开发的工作量和困难而swagger的出现就是为了解决这一系列的问题。Swagger是一系列用于RESTful API开发的工具。
导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.1</version>
</dependency>
配置Swagger
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//分组的名字
.groupName("yu")
//设置为哪些目标接口生成接口文档
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
//任意路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
//作者信息
Contact contact = new Contact("yu", "https://blog.csdn.net/qq_43649937?type=blog", "2248406167@qq.com");
return new ApiInfo(
"yu的swaggerAPI文档",
"11",
"v1.0",
"https://blog.csdn.net/qq_43649937?type=blog",
contact,
"Apache2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
然后访问http://localhost:8080/swagger-ui.html就可以访问 swagger界面了在这里我在运行 时出现了以下这样的问题org.springframework.context.ApplicationContextException: Failed to start bean
在经过查资料得以解决这个问题Springfox使用的路径匹配是基于AntPathMatcher的而Spring Boot 2.6.X使用的是PathPatternMatcher因此需要在application.properties里配置spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER 最终问题得以解决。
然后就是如果配置了拦截器记住一定要放行swagger,不然无法访问在拦截器配置中放行路径如下
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
Swagger常用注解
@Api()用于类
表示标识这个类是swagger的资源 @Api 注解用于标注一个ControllerClass
@ApiOperation()用于方法
表示一个http请求的操作
@ApiParam()用于方法参数字段说明
表示对参数的添加元数据说明或是否必填等
@ApiModel()用于类
表示对类进行说明用于参数用实体类接收
@ApiModelProperty()用于方法字段
表示对model属性的说明或者数据操作更改
@ApiIgnore()用于类方法方法参数
表示这个方法或者类被忽略
@ApiImplicitParam() 用于方法
表示单独的请求参数
@ApiImplicitParams() 用于方法包含多个 @ApiImplicitParam