一、自定义starter–Swagger&Knife4J封装
1、添加依赖
创建项目xxx-swagger2-starter
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${swagger.version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
2、添加配置类
@Data
@ConfigurationProperties("iocode.swagger")
public class SwaggerProperties {
private Boolean enabled = false;
private String title = "";
private String description = "";
private String version = "";
private String basePackage = "";
private Contact contact = new Contact();
@Data
public static class Contact {
private String name = "";
private String url = "";
private String email = "";
}
}
//配置类
@EnableSwagger2
@Configuration
@EnableConfigurationProperties({SwaggerProperties.class})
public class SwaggerAutoConfiguration {
@Autowired
private SwaggerProperties swaggerProperties;
@Bean
public Docket createRestApi() {
if (swaggerProperties == null || swaggerProperties.getEnabled() == null) {
return new Docket(DocumentationType.SWAGGER_2).enable(false);
}
return new Docket(DocumentationType.SWAGGER_2)
.enable(swaggerProperties.getEnabled())
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(
swaggerProperties.getBasePackage()))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
Contact contact = new Contact(swaggerProperties.getContact().getName(),
swaggerProperties.getContact().getUrl(),
swaggerProperties.getContact().getEmail());
return new ApiInfoBuilder()
.title(swaggerProperties.getTitle())
.description(swaggerProperties.getDescription())
.contact(contact)
.version(swaggerProperties.getVersion())
.build();
}
}
3、添加spring.factories
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
cn.common.swagger2.SwaggerAutoConfiguration
4、其他项目中引入swagger以及配置
(1)添加依赖
<dependency>
<groupId>cn.xcode</groupId>
<artifactId>xcode-iocode-swagger2-starter</artifactId>
</dependency>
(2)添加配置
xcode:
iocode:
swagger:
enabled: true
title: "xcode-iocode-course 接口文档"
description: "豌豆编程CourseB接口文档"
version: 1.0
basePackage: cn.iocode.course.controller
contact:
name: "豌豆编程开发组"
url: "http://dev-iocode.cn"
email: "dev-iocode@happy-seed.com"