springboot配置swagger
不久之前配置过swagger,因为比较顺利,懒得去记录,结果今天再配置的时候,各种坑,浪费了两个小时,牢记教训,还是记一下。
首先说一下为什么添加swagger模块,对于api项目来说,接口的管理和测试对于使用方来说,不怎么友好;为缓解这个问题,这才有了swagger。
接下来说一下配置步骤:
①、添加依赖
<!-- swagger --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
②、将swagger模块加载到spring上下文
1 @Configuration 2 @EnableSwagger2 3 public class Swagger2Config { 4 5 @Bean 6 public Docket createRestApi() { 7 return new Docket(DocumentationType.SWAGGER_2) 8 .apiInfo(apiInfo()) 9 // select()函数返回一个ApiSelectorBuilder实例用来构建Docket 10 .select() 11 // Swagger会扫描该包下所有Controller定义的API,并产生文档内容 12 .apis(RequestHandlerSelectors.basePackage("com.test.api")) 13 // 不需要过滤接口 14 .paths(PathSelectors.any()) 15 .build(); 16 } 17 18 /** 19 * Api的基本信息(这些基本信息会展现在文档页面中) 20 */ 21 private ApiInfo apiInfo() { 22 return new ApiInfoBuilder() 23 .title("数据API") 24 .description("data REST API, all the applications could access the data via JSON.") 25 .version("1.0") 26 .build(); 27 } 28 }