上回咋们说到,spring boot 的web开发,使用swagger作为接口测试工具,不知道大家又没有发现一个小问题,就是swagger需要在config类中配置一个Docket bean,还要引入相对的jar包,那每次构建web项目都需要这些重新再写一次?不用,spring boot启动器是用来干什么的,不就是自动集成么,现在我们就来自定义一个swagger的启动器。
启动器
第一回咋们说道,spring boot starter实现的一个核心是啥,spring.factories嘛。首先新建一个swagger-spring-boot-starter maven项目。
xxx-spring-boot-starter是spring boot的建议命名规则,为了和官方的spring-boot-starter-xxx做区分。
项目已经有了,开始撸。。。
创建swagger config配置项
@ConfigurationProperties(prefix = "spring.swagger") //创建配置项,并读取文件以spring.swagger开头的配置参数
@ConditionalOnWebApplication //在web环境下创建此项配置
@EnableSwagger2
public class swagger {
private String basePackage;
private String title;
private String version;
[@Bean](https://my.oschina.net/bean)
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(basePackage))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title(title)
.version(version)
.build();
}
public void setBasePackage(String basePackage) {
this.basePackage = basePackage;
}
public void setTitle(String title) {
this.title = title;
}
public void setVersion(String version) {
this.version = version;
}
}
在resources目录下创建META-INF/spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.le.swagger
然后打包,在我们的web项目中去掉关于swagger的引入,并重新引入我们的swagger-spring-boot-starter包
<dependency>
<groupId>cn.le</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
然后在web项目中的配置文件中加入我们swagger-spring-boot-starter的配置参数
spring.swagger.basePackage=cn.le
#只能识别unicode码
spring.swagger.title=\u81ea\u5b9a\u4e49\u0073\u0077\u0061\u0067\u0067\u0065\u0072\u0020\u0073\u0074\u0061\u0072\u0074\u0065\u0072
spring.swagger=1.0
然后启动项目,访问swagger-ui.html
搞定,是不是很简单。
-------代码 git 地址 https://gitee.com/distant/spring-boot-geit.git