As we mentioned last time, the web development of spring boot uses swagger as an interface testing tool. I don’t know if you haven’t found a small problem, that is, swagger needs to configure a Docket bean in the config class, and also introduces a relative jar package. Do you need to rewrite these every time you build a web project? No, what the spring boot starter is used for, isn't it automatic integration, now let's customize a swagger starter.
Launcher
The first time we said, what is the core of spring boot starter implementation, spring.factories. First create a new swagger-spring-boot-starter maven project.
xxx-spring-boot-starter is the recommended naming convention of spring boot, in order to distinguish it from the official spring-boot-starter-xxx.
The project already exists, let's start rolling. . .
Create swagger config configuration item
@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;
}
}
Create META-INF/spring.factories in the resources directory
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.le.swagger
Then package, remove the introduction of swagger in our web project, and re-introduce our swagger-spring-boot-starter package
<dependency>
<groupId>cn.le</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
Then add the configuration parameters of our swagger-spring-boot-starter to the configuration file in the web project
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
Then start the project and visit swagger-ui.html
Get it, isn't it easy.
-------code git address https://gitee.com/distant/spring-boot-geit.git