init project v1.0.0

This commit is contained in:
zlt
2019-01-19 15:31:26 +08:00
parent 5c1cdaa54e
commit 19fecc3b05
728 changed files with 65634 additions and 0 deletions
@@ -0,0 +1,2 @@
/target/
*.iml
@@ -0,0 +1,136 @@
# 简介
该项目主要利用Spring Boot的自动化配置特性来实现快速的将swagger2引入spring boot应用来生成API文档,简化原生使用swagger2的整合代码。
# 如何使用
dependency引入即可。默认情况下就能产生所有当前Spring MVC加载的请求映射文档。
## 配置示例
```properties
swagger.enabled=true
swagger.title=spring-boot-starter-swagger
swagger.description=Starter for swagger 2.x
swagger.version=1.4.0.RELEASE
swagger.license=Apache License, Version 2.0
swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html
swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger
swagger.contact.name=didi
swagger.contact.url=http://blog.didispace.com
swagger.contact.email=dyc87112@qq.com
swagger.base-package=com.didispace
swagger.base-path=/**
swagger.exclude-path=/error, /ops/**
swagger.globalOperationParameters[0].name=name one
swagger.globalOperationParameters[0].description=some description one
swagger.globalOperationParameters[0].modelRef=string
swagger.globalOperationParameters[0].parameterType=header
swagger.globalOperationParameters[0].required=true
swagger.globalOperationParameters[1].name=name two
swagger.globalOperationParameters[1].description=some description two
swagger.globalOperationParameters[1].modelRef=string
swagger.globalOperationParameters[1].parameterType=body
swagger.globalOperationParameters[1].required=false
```
## 配置说明
### 默认配置
```
- swagger.enabled=是否启用swagger,默认:true
- swagger.title=标题
- swagger.description=描述
- swagger.version=版本
- swagger.license=许可证
- swagger.licenseUrl=许可证URL
- swagger.termsOfServiceUrl=服务条款URL
- swagger.contact.name=维护人
- swagger.contact.url=维护人URL
- swagger.contact.email=维护人email
- swagger.base-package=swagger扫描的基础包,默认:全扫描
- swagger.base-path=需要处理的基础URL规则,默认:/**
- swagger.exclude-path=需要排除的URL规则,默认:空
- swagger.host=文档的host信息,默认:空
- globalOperationParameters用于设置全局的参数,比如:header部分的accessToken等。该参数支持指定docket的配置。
- swagger.globalOperationParameters[0].name=参数名
- swagger.globalOperationParameters[0].description=描述信息
- swagger.globalOperationParameters[0].modelRef=指定参数类型
- swagger.globalOperationParameters[0].parameterType=指定参数存放位置,可选header,query,path,body.form
- swagger.globalOperationParameters[0].required=指定参数是否必传,true,false
```
### Path规则说明
`swagger.base-path`和`swagger.exclude-path`使用ANT规则配置。
我们可以使用`swagger.base-path`来指定所有需要生成文档的请求路径基础规则,然后再利用`swagger.exclude-path`来剔除部分我们不需要的。
比如,通常我们可以这样设置:
```properties
management.context-path=/ops
swagger.base-path=/**
swagger.exclude-path=/ops/**, /error
```
上面的设置将解析所有除了`/ops/`开始以及spring boot自带`/error`请求路径。
其中,`exclude-path`可以配合`management.context-path=/ops`设置的spring boot actuator的context-path来排除所有监控端点。
### 分组配置
当我们一个项目的API非常多的时候,我们希望对API文档实现分组。从1.2.0.RELEASE开始,将支持分组配置功能。
![分组功能](https://github.com/dyc87112/spring-boot-starter-swagger/blob/master/images/swagger-group.png)
具体配置内容如下:
```
- swagger.docket.<name>.title=标题
- swagger.docket.<name>.description=描述
- swagger.docket.<name>.version=版本
- swagger.docket.<name>.license=许可证
- swagger.docket.<name>.licenseUrl=许可证URL
- swagger.docket.<name>.termsOfServiceUrl=服务条款URL
- swagger.docket.<name>.contact.name=维护人
- swagger.docket.<name>.contact.url=维护人URL
- swagger.docket.<name>.contact.email=维护人email
- swagger.docket.<name>.base-package=swagger扫描的基础包,默认:全扫描
- swagger.docket.<name>.base-path=需要处理的基础URL规则,默认:/**
- swagger.docket.<name>.exclude-path=需要排除的URL规则,默认:空
- swagger.docket.<name>.name=参数名
- swagger.docket.<name>.modelRef=指定参数类型
- swagger.docket.<name>.parameterType=指定参数存放位置,可选header,query,path,body.form
- swagger.docket.<name>.required=true=指定参数是否必传,true,false
- swagger.docket.<name>.globalOperationParameters[0].name=参数名
- swagger.docket.<name>.globalOperationParameters[0].description=描述信息
- swagger.docket.<name>.globalOperationParameters[0].modelRef=指定参数存放位置,可选header,query,path,body.form
- swagger.docket.<name>.globalOperationParameters[0].parameterType=指定参数是否必传,true,false
```
说明:`<name>`为swagger文档的分组名称,同一个项目中可以配置多个分组,用来划分不同的API文档。
**分组配置示例**
```properties
swagger.docket.aaa.title=group-a
swagger.docket.aaa.description=Starter for swagger 2.x
swagger.docket.aaa.version=1.3.0.RELEASE
swagger.docket.aaa.termsOfServiceUrl=https://gitee.com/didispace/spring-boot-starter-swagger
swagger.docket.aaa.contact.name=zhaiyongchao
swagger.docket.aaa.contact.url=http://spring4all.com/
swagger.docket.aaa.contact.email=didi@potatomato.club
swagger.docket.aaa.excludePath=/ops/**
swagger.docket.aaa.globalOperationParameters[0].name=name three
swagger.docket.aaa.globalOperationParameters[0].description=some description three override
swagger.docket.aaa.globalOperationParameters[0].modelRef=string
swagger.docket.aaa.globalOperationParameters[0].parameterType=header
swagger.docket.bbb.title=group-bbb
swagger.docket.bbb.basePackage=com.yonghui
```
说明:默认配置与分组配置可以一起使用。在分组配置中没有配置的内容将使用默认配置替代,所以默认配置可以作为分组配置公共部分属性的配置。`swagger.docket.aaa.globalOperationParameters[0].name`会覆盖同名的全局配置。
@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>com.zlt</groupId>
<artifactId>zlt-commons</artifactId>
<version>1.0.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<packaging>jar</packaging>
<artifactId>zlt-swagger2-spring-boot-starter</artifactId>
<description>swagger通用组件</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,19 @@
package com.central.common.swagger2;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.swagger2.configuration.Swagger2DocumentationConfiguration;
/**
*
* @author zlt
* @date 2018/11/18 9:20
*/
@Configuration
@ConditionalOnProperty(name = "zlt.swagger.enabled", matchIfMissing = true)
@Import({
Swagger2DocumentationConfiguration.class
})
public class Swagger2Configuration {
}
@@ -0,0 +1,265 @@
package com.central.common.swagger2;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author zlt
* @date 2018/11/18 9:22
*/
@Configuration
@Import( {
Swagger2Configuration.class
})
public class SwaggerAutoConfiguration implements BeanFactoryAware {
private BeanFactory beanFactory;
@Bean
@ConditionalOnMissingBean
public SwaggerProperties swaggerProperties() {
return new SwaggerProperties();
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = "zlt.swagger.enabled", matchIfMissing = true)
public List<Docket> createRestApi(SwaggerProperties swaggerProperties) {
ConfigurableBeanFactory configurableBeanFactory = (ConfigurableBeanFactory) beanFactory;
List<Docket> docketList = new LinkedList<>();
// 没有分组
if (swaggerProperties.getDocket().size() == 0) {
final Docket docket = createDocket(swaggerProperties);
configurableBeanFactory.registerSingleton("defaultDocket", docket);
docketList.add(docket);
return docketList;
}
// 分组创建
for (String groupName : swaggerProperties.getDocket().keySet()) {
SwaggerProperties.DocketInfo docketInfo = swaggerProperties.getDocket().get(groupName);
ApiInfo apiInfo = new ApiInfoBuilder()
.title(docketInfo.getTitle().isEmpty() ? swaggerProperties.getTitle() : docketInfo.getTitle())
.description(docketInfo.getDescription().isEmpty() ? swaggerProperties.getDescription() : docketInfo.getDescription())
.version(docketInfo.getVersion().isEmpty() ? swaggerProperties.getVersion() : docketInfo.getVersion())
.license(docketInfo.getLicense().isEmpty() ? swaggerProperties.getLicense() : docketInfo.getLicense())
.licenseUrl(docketInfo.getLicenseUrl().isEmpty() ? swaggerProperties.getLicenseUrl() : docketInfo.getLicenseUrl())
.contact(
new Contact(
docketInfo.getContact().getName().isEmpty() ? swaggerProperties.getContact().getName() : docketInfo.getContact().getName(),
docketInfo.getContact().getUrl().isEmpty() ? swaggerProperties.getContact().getUrl() : docketInfo.getContact().getUrl(),
docketInfo.getContact().getEmail().isEmpty() ? swaggerProperties.getContact().getEmail() : docketInfo.getContact().getEmail()
)
)
.termsOfServiceUrl(docketInfo.getTermsOfServiceUrl().isEmpty() ? swaggerProperties.getTermsOfServiceUrl() : docketInfo.getTermsOfServiceUrl())
.build();
// base-path处理
// 当没有配置任何path的时候,解析/**
if (docketInfo.getBasePath().isEmpty()) {
docketInfo.getBasePath().add("/**");
}
List<Predicate<String>> basePath = new ArrayList<>(docketInfo.getBasePath().size());
for (String path : docketInfo.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List<Predicate<String>> excludePath = new ArrayList<>(docketInfo.getExcludePath().size());
for (String path : docketInfo.getExcludePath()) {
excludePath.add(PathSelectors.ant(path));
}
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.host(swaggerProperties.getHost())
.apiInfo(apiInfo)
.globalOperationParameters(assemblyGlobalOperationParameters(swaggerProperties.getGlobalOperationParameters(),
docketInfo.getGlobalOperationParameters()))
.groupName(groupName)
.select()
.apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
.paths(
Predicates.and(
Predicates.not(Predicates.or(excludePath)),
Predicates.or(basePath)
)
)
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
configurableBeanFactory.registerSingleton(groupName, docket);
docketList.add(docket);
}
return docketList;
}
/**
* 创建 Docket对象
*
* @param swaggerProperties swagger配置
* @return Docket
*/
private Docket createDocket(final SwaggerProperties swaggerProperties) {
ApiInfo apiInfo = new ApiInfoBuilder()
.title(swaggerProperties.getTitle())
.description(swaggerProperties.getDescription())
.version(swaggerProperties.getVersion())
.license(swaggerProperties.getLicense())
.licenseUrl(swaggerProperties.getLicenseUrl())
.contact(new Contact(swaggerProperties.getContact().getName(),
swaggerProperties.getContact().getUrl(),
swaggerProperties.getContact().getEmail()))
.termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl())
.build();
// base-path处理
// 当没有配置任何path的时候,解析/**
if (swaggerProperties.getBasePath().isEmpty()) {
swaggerProperties.getBasePath().add("/**");
}
List<Predicate<String>> basePath = new ArrayList<>();
for (String path : swaggerProperties.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List<Predicate<String>> excludePath = new ArrayList<>();
for (String path : swaggerProperties.getExcludePath()) {
excludePath.add(PathSelectors.ant(path));
}
return new Docket(DocumentationType.SWAGGER_2)
.host(swaggerProperties.getHost())
.apiInfo(apiInfo)
.globalOperationParameters(buildGlobalOperationParametersFromSwaggerProperties(
swaggerProperties.getGlobalOperationParameters()))
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
.paths(
Predicates.and(
Predicates.not(Predicates.or(excludePath)),
Predicates.or(basePath)
)
)
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> contexts = new ArrayList<>(1);
SecurityContext securityContext = SecurityContext.builder()
.securityReferences(defaultAuth())
//.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build();
contexts.add(securityContext);
return contexts;
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> references = new ArrayList<>(1);
references.add(new SecurityReference("Authorization", authorizationScopes));
return references;
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeys = new ArrayList<>(1);
ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
apiKeys.add(apiKey);
return apiKeys;
}
private List<Parameter> buildGlobalOperationParametersFromSwaggerProperties(
List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters) {
List<Parameter> parameters = Lists.newArrayList();
if (Objects.isNull(globalOperationParameters)) {
return parameters;
}
for (SwaggerProperties.GlobalOperationParameter globalOperationParameter : globalOperationParameters) {
parameters.add(new ParameterBuilder()
.name(globalOperationParameter.getName())
.description(globalOperationParameter.getDescription())
.modelRef(new ModelRef(globalOperationParameter.getModelRef()))
.parameterType(globalOperationParameter.getParameterType())
.required(Boolean.parseBoolean(globalOperationParameter.getRequired()))
.build());
}
return parameters;
}
/**
* 局部参数按照name覆盖局部参数
*
* @param globalOperationParameters
* @param docketOperationParameters
* @return
*/
private List<Parameter> assemblyGlobalOperationParameters(
List<SwaggerProperties.GlobalOperationParameter> globalOperationParameters,
List<SwaggerProperties.GlobalOperationParameter> docketOperationParameters) {
if (Objects.isNull(docketOperationParameters) || docketOperationParameters.isEmpty()) {
return buildGlobalOperationParametersFromSwaggerProperties(globalOperationParameters);
}
Set<String> docketNames = docketOperationParameters.stream()
.map(SwaggerProperties.GlobalOperationParameter::getName)
.collect(Collectors.toSet());
List<SwaggerProperties.GlobalOperationParameter> resultOperationParameters = Lists.newArrayList();
if (Objects.nonNull(globalOperationParameters)) {
for (SwaggerProperties.GlobalOperationParameter parameter : globalOperationParameters) {
if (!docketNames.contains(parameter.getName())) {
resultOperationParameters.add(parameter);
}
}
}
resultOperationParameters.addAll(docketOperationParameters);
return buildGlobalOperationParametersFromSwaggerProperties(resultOperationParameters);
}
}
@@ -0,0 +1,150 @@
package com.central.common.swagger2;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* swagger2 属性配置
*
* @author zlt
* @date 2018/11/18 9:17
*/
@Data
@ConfigurationProperties("zlt.swagger")
public class SwaggerProperties {
/**是否开启swagger**/
private Boolean enabled;
/**标题**/
private String title = "";
/**描述**/
private String description = "";
/**版本**/
private String version = "";
/**许可证**/
private String license = "";
/**许可证URL**/
private String licenseUrl = "";
/**服务条款URL**/
private String termsOfServiceUrl = "";
private Contact contact = new Contact();
/**swagger会解析的包路径**/
private String basePackage = "";
/**swagger会解析的url规则**/
private List<String> basePath = new ArrayList<>();
/**在basePath基础上需要排除的url规则**/
private List<String> excludePath = new ArrayList<>();
/**分组文档**/
private Map<String, DocketInfo> docket = new LinkedHashMap<>();
/**host信息**/
private String host = "";
/**全局参数配置**/
private List<GlobalOperationParameter> globalOperationParameters;
public static class GlobalOperationParameter{
/**参数名**/
private String name;
/**描述信息**/
private String description;
/**指定参数类型**/
private String modelRef;
/**参数放在哪个地方:header,query,path,body.form**/
private String parameterType;
/**参数是否必须传**/
private String required;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getModelRef() {
return modelRef;
}
public void setModelRef(String modelRef) {
this.modelRef = modelRef;
}
public String getParameterType() {
return parameterType;
}
public void setParameterType(String parameterType) {
this.parameterType = parameterType;
}
public String getRequired() {
return required;
}
public void setRequired(String required) {
this.required = required;
}
}
@Data
public static class DocketInfo {
/**标题**/
private String title = "";
/**描述**/
private String description = "";
/**版本**/
private String version = "";
/**许可证**/
private String license = "";
/**许可证URL**/
private String licenseUrl = "";
/**服务条款URL**/
private String termsOfServiceUrl = "";
private Contact contact = new Contact();
/**swagger会解析的包路径**/
private String basePackage = "";
/**swagger会解析的url规则**/
private List<String> basePath = new ArrayList<>();
/**在basePath基础上需要排除的url规则**/
private List<String> excludePath = new ArrayList<>();
private List<GlobalOperationParameter> globalOperationParameters;
}
@Data
public static class Contact {
/**联系人**/
private String name = "";
/**联系人url**/
private String url = "";
/**联系人email**/
private String email = "";
}
}
@@ -0,0 +1,2 @@
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.central.common.swagger2.SwaggerAutoConfiguration