@Configuration
@EnableSwagger2
@EnableConfigurationProperties(Swagger2Config.class)
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {
// swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket createRestApi(Swagger2Config swagger2Config) {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo(swagger2Config))
.select()
// 自定义匹配带 * 号的路径
.apis(this.basePackage(swagger2Config.getBasePackage()))
.paths(PathSelectors.any())
.build();
}
// 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo(Swagger2Config swagger2Config) {
return new ApiInfoBuilder()
// 页面标题
.title(swagger2Config.getTitle())
// 创建人信息
.contact(swagger2Config.getContact().build())
// 版本号
.version(swagger2Config.getVersion())
// 描述
.description(swagger2Config.getDescription())
.build();
}
private Predicate<RequestHandler> basePackage(String basePackage) {
return input -> Optional.fromNullable(input.declaringClass())
.transform((Function<Class<?>, Boolean>) input1 -> StringUtil.match(basePackage, ClassUtils.getPackageName(input1))).or(false);
}
}
自己实现匹配 * 号的包路径
public class StringUtil {
/**
* 匹配 *
* @param basePackage
* @param path
* @return
*/
public static boolean match(String basePackage, String path) {
boolean anyBlank = StringUtils.isAnyBlank(basePackage, path);
if (anyBlank) {
return false;
}
int basePackageLength = basePackage.length();
int basePackagePos = 0;
int pathLength = path.length();
int pathPos = 0;
while (pathPos < pathLength && basePackagePos < basePackageLength) {
char bc = basePackage.charAt(basePackagePos);
char pc = path.charAt(pathPos);
if (bc == '*' && pc != '.') {
pathPos++;
continue;
}
//将后面 . 跳过
if (bc == '*') {
basePackagePos++;
bc = basePackage.charAt(basePackagePos);
}
if (bc != pc) {
break;
}
pathPos++;
basePackagePos++;
}
return basePackagePos == basePackageLength && pathPos == pathLength;
}
}
@ConfigurationProperties(prefix = "swagger")
@Data
public class Swagger2Config {
private String title;
private String basePackage;
private String version;
private String description;
private ContactInfo contact;
@Data
public static class ContactInfo {
private String name;
private String url;
private String email;
public Contact build() {
return new Contact(this.name, this.url, this.email);
}
}
}
其他模块中直接引入即可
server:
port: 9000
servlet:
context-path: /user-center
spring:
application:
name: USER-CENTER
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://master:3306/user_center
username: root
password: root
swagger:
enable: true
title: "用户中心"
basePackage: "com.xxx.xxx.controller"
version: "1.0.0"
description: "用户中心api"
contact:
name: "name"
url: "http://ip:port/url"
email: "xxxxx@qq.com"
mybatis:
mapper-locations: classpath*:mapper/*.xml