在前后端分离开发的过程中,前端和后端需要进行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 注解用于标注一个Controller(Class)
@ApiOperation()用于方法;
表示一个http请求的操作
@ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等)
@ApiModel()用于类
表示对类进行说明,用于参数用实体类接收
@ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改
@ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
@ApiImplicitParam() 用于方法
表示单独的请求参数
@ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam