写在前面
前后端分离的项目中,使用 Swagger2 来构建在线接口文档是必不可少的,如果所有的微服务都配置SWAGGER2的信息太麻烦了,所以接下来一步一步的带着大家构建统一的SWAGGER组件。
在阅读该博文前需要先了解以下内容:
JAVA8 - java.util.function.Predicate
SpringBoot - spring.factories的作用是什么?
SpringBoot - Swagger2的集成与使用(一)
如何创建
1. 创建一个单独的模块(servicex-common-swagger)
2. 在该模块中引入依赖
<!-- SpringBoot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<!-- Swagger UI -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<!-- lombok 工具 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
3. 自定义SWAGGER2注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({SwaggerAutoConfiguration.class})
public @interface EnableServiceSwagger2 {
}
4. 创建自动装配SWAGGER2的对象
@Configuration
@EnableSwagger2
@EnableAutoConfiguration
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
public class SwaggerAutoConfiguration {
// 默认的排除路径, 排除SPRING BOOT默认的错误处理路径和端点
private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/**");
private static final String BASE_PATH = "/**";
@Bean
@ConditionalOnMissingBean
public SwaggerProperties swaggerProperties() {
return new SwaggerProperties();
}
@Bean
public Docket api(SwaggerProperties swaggerProperties) {
// base-path处理
if (swaggerProperties.getBasePath().isEmpty()) {
swaggerProperties.getBasePath().add(BASE_PATH);
}
// SWAGGER会解析的URL规则的处理, 将配置的需要解析的URL规则放进LIST中
List<Predicate<String>> basePath = new ArrayList<Predicate<String>>();
swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path)));
// 在BASE-PAHT基础上需要排除的URL规则的处理, 将配置的需要排除的URL规则放进LIST中
if (swaggerProperties.getExcludePath().isEmpty()) {
swaggerProperties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH);
}
List<Predicate<String>> excludePath = new ArrayList<>();
swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));
return new Docket(DocumentationType.SWAGGER_2)
.host(swaggerProperties.getHost())
// 在API-INFO中构建文档的基本信息. 例如描述、联系人信息、版本、标题等
.apiInfo(apiInfo(swaggerProperties)).select()
// 通过APIS方法配置要扫描的CONTROLLER的位置(会解析的包路径)
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
// [GUVA]通过PATHS方法配置路径(会解析的URL规则, 需要在BASE-PAHT的基础上排除不需要解析的URL规则)
.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)), Predicates.or(basePath)))
.build()
.pathMapping("/");
}
// 文档基本信息
private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
return new ApiInfoBuilder()
.title(swaggerProperties.getTitle())
.description(swaggerProperties.getDescription())
.license(swaggerProperties.getLicense())
.licenseUrl(swaggerProperties.getLicenseUrl())
.termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
.contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail()))
.version(swaggerProperties.getVersion())
.build();
}
}
5. 创建SWAGGER2配置对象
@Data
@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties {
// 是否开启SWAGGER2
private Boolean enabled;
// SWAGGER会解析的包路径
private String basePackage = "";
// SWAGGER会解析的URL规则
private List<String> basePath = new ArrayList<>();
// 在BASE-PAHT基础上需要排除的URL规则
private List<String> excludePath = new ArrayList<>();
// 文档标题(如: 广告服务接口文档)
private String title = "";
// 文档描述(如: 该文档用于描述广告服务提供的接口)
private String description = "";
// 文档的版本
private String version = "1.0";
// 许可证
private String license = "Powered By hadoopx";
// 许可证URL
private String licenseUrl = "http://hadoopx.cn";
// 服务条款URL
private String termsOfServiceUrl = "";
// HOST信息
private String host = "";
// 联系人信息
private Contact contact = new Contact();
// 全局统一鉴权配置
private Authorization authorization = new Authorization();
@Data
public static class Contact {
// 联系人
private String name = "ROCKY";
// 联系人URL
private String url = "";
// 联系人邮箱
private String email = "";
}
@Data
public static class Authorization {
// 鉴权策略ID,需要和SecurityReferences ID保持一致
private String name = "";
// 需要开启鉴权URL的正则
private String authRegex = "^.*$";
// 鉴权作用域列表
private List<AuthorizationScope> authorizationScopeList = new ArrayList<>();
private List<String> tokenUrlList = new ArrayList<>();
}
@Data
public static class AuthorizationScope {
// 作用域名称
private String scope = "";
// 作用域描述
private String description = "";
}
}
6. 配置场景启动器的加载策略
// 在resources/META-INF/spring.factories的文件中添加如下配置:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.hadoopx.common.swagger.config.SwaggerAutoConfiguration
7. 编译打包…
如何使用
1. 引入依赖, 在微服务的POM.XML中添加如下依赖
<!-- SWAGGER注解 -->
<dependency>
<groupId>com.hadoopx</groupId>
<artifactId>servicex-common-swagger</artifactId>
<version>${servicex.version}</version>
</dependency>
2. 添加注解, 在微服务的启动类中添加如下依赖
@EnableServiceSwagger2
3. 在线API文档
http://微服务的IP或者LOCALHOST:微服务的端口号/swagger-ui.html