├── images ├── jsr-303.png └── swagger-group.png ├── .travis.yml ├── src └── main │ ├── resources │ └── META-INF │ │ └── spring.factories │ └── java │ └── com │ └── spring4all │ └── swagger │ ├── SwaggerAutoConfiguration.java │ ├── SwaggerAuthorizationProperties.java │ ├── PathSelectors.java │ ├── SwaggerUiConfiguration.java │ ├── SwaggerUiProperties.java │ ├── SwaggerAuthorizationConfiguration.java │ ├── SwaggerProperties.java │ └── DocketConfiguration.java ├── .gitignore ├── pom.xml ├── LICENSE └── README.md /images/jsr-303.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lcomplete/spring-boot-starter-swagger/master/images/jsr-303.png -------------------------------------------------------------------------------- /images/swagger-group.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lcomplete/spring-boot-starter-swagger/master/images/swagger-group.png -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: java 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | install: mvn install -DskipTests=true -Dmaven.javadoc.skip=true 7 | -------------------------------------------------------------------------------- /src/main/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | com.spring4all.swagger.SwaggerAutoConfiguration -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | 12 | ### IntelliJ IDEA ### 13 | .idea 14 | *.iws 15 | *.iml 16 | *.ipr 17 | 18 | ### NetBeans ### 19 | nbproject/private/ 20 | build/ 21 | nbbuild/ 22 | dist/ 23 | nbdist/ 24 | .nb-gradle/ -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/SwaggerAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | import org.springframework.context.annotation.Import; 6 | 7 | /** 8 | * @author 翟永超 9 | * Create date:2017/8/7. 10 | * My blog: http://blog.didispace.com 11 | */ 12 | @Configuration 13 | @EnableConfigurationProperties(SwaggerProperties.class) 14 | @Import({ 15 | SwaggerUiConfiguration.class, 16 | SwaggerAuthorizationConfiguration.class, 17 | DocketConfiguration.class 18 | }) 19 | public class SwaggerAutoConfiguration { 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/SwaggerAuthorizationProperties.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import lombok.Data; 4 | import org.springframework.boot.context.properties.ConfigurationProperties; 5 | import springfox.documentation.swagger.web.DocExpansion; 6 | import springfox.documentation.swagger.web.ModelRendering; 7 | import springfox.documentation.swagger.web.OperationsSorter; 8 | import springfox.documentation.swagger.web.TagsSorter; 9 | 10 | /** 11 | * @author 翟永超 12 | * Create date :2017/8/7. 13 | * My blog: http://blog.didispace.com 14 | */ 15 | @Data 16 | @ConfigurationProperties("swagger.authorization") 17 | public class SwaggerAuthorizationProperties { 18 | 19 | /** 20 | * 鉴权策略ID,对应 SecurityReferences ID 21 | */ 22 | private String name = "Authorization"; 23 | 24 | /** 25 | * 鉴权策略,可选 ApiKey | BasicAuth | None,默认ApiKey 26 | */ 27 | private String type = "ApiKey"; 28 | 29 | /** 30 | * 鉴权传递的Header参数 31 | */ 32 | private String keyName = "TOKEN"; 33 | 34 | /** 35 | * 需要开启鉴权URL的正则 36 | */ 37 | private String authRegex = "^.*$"; 38 | 39 | } 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/PathSelectors.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import com.google.common.base.Predicate; 4 | import com.google.common.base.Predicates; 5 | import org.springframework.util.AntPathMatcher; 6 | 7 | public class PathSelectors { 8 | private PathSelectors() { 9 | throw new UnsupportedOperationException(); 10 | } 11 | 12 | /** 13 | * Any path satisfies this condition 14 | * 15 | * @return predicate that is always true 16 | */ 17 | public static Predicate any() { 18 | return Predicates.alwaysTrue(); 19 | } 20 | 21 | /** 22 | * No path satisfies this condition 23 | * 24 | * @return predicate that is always false 25 | */ 26 | public static Predicate none() { 27 | return Predicates.alwaysFalse(); 28 | } 29 | 30 | /** 31 | * Predicate that evaluates the supplied regular expression 32 | * 33 | * @param pathRegex - regex 34 | * @return predicate that matches a particular regex 35 | */ 36 | public static Predicate regex(final String pathRegex) { 37 | return new Predicate() { 38 | @Override 39 | public boolean apply(String input) { 40 | return input.matches(pathRegex); 41 | } 42 | }; 43 | } 44 | 45 | /** 46 | * Predicate that evaluates the supplied ant pattern 47 | * 48 | * @param antPattern - ant Pattern 49 | * @return predicate that matches a particular ant pattern 50 | */ 51 | public static Predicate ant(final String antPattern) { 52 | return new Predicate() { 53 | @Override 54 | public boolean apply(String input) { 55 | AntPathMatcher matcher = new AntPathMatcher(); 56 | return matcher.match(antPattern, input); 57 | } 58 | }; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/SwaggerUiConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Bean; 5 | import org.springframework.context.annotation.Configuration; 6 | import org.springframework.context.annotation.Import; 7 | import springfox.documentation.swagger.web.UiConfiguration; 8 | import springfox.documentation.swagger.web.UiConfigurationBuilder; 9 | 10 | /** 11 | * @author 翟永超 12 | * Create date:2017/8/7. 13 | * My blog: http://blog.didispace.com 14 | */ 15 | @Configuration 16 | @EnableConfigurationProperties(SwaggerUiProperties.class) 17 | public class SwaggerUiConfiguration { 18 | 19 | @Bean 20 | public UiConfiguration uiConfiguration(SwaggerUiProperties swaggerUiProperties) { 21 | return UiConfigurationBuilder.builder() 22 | .deepLinking(swaggerUiProperties.getDeepLinking()) 23 | .defaultModelExpandDepth(swaggerUiProperties.getDefaultModelExpandDepth()) 24 | .defaultModelRendering(swaggerUiProperties.getDefaultModelRendering()) 25 | .defaultModelsExpandDepth(swaggerUiProperties.getDefaultModelsExpandDepth()) 26 | .displayOperationId(swaggerUiProperties.getDisplayOperationId()) 27 | .displayRequestDuration(swaggerUiProperties.getDisplayRequestDuration()) 28 | .docExpansion(swaggerUiProperties.getDocExpansion()) 29 | .maxDisplayedTags(swaggerUiProperties.getMaxDisplayedTags()) 30 | .operationsSorter(swaggerUiProperties.getOperationsSorter()) 31 | .showExtensions(swaggerUiProperties.getShowExtensions()) 32 | .tagsSorter(swaggerUiProperties.getTagsSorter()) 33 | .validatorUrl(swaggerUiProperties.getValidatorUrl()) 34 | .build(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/SwaggerUiProperties.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | import springfox.documentation.swagger.web.DocExpansion; 7 | import springfox.documentation.swagger.web.ModelRendering; 8 | import springfox.documentation.swagger.web.OperationsSorter; 9 | import springfox.documentation.swagger.web.TagsSorter; 10 | 11 | import java.util.ArrayList; 12 | import java.util.LinkedHashMap; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | /** 17 | * @author 翟永超 18 | * Create date :2017/8/7. 19 | * My blog: http://blog.didispace.com 20 | */ 21 | @Data 22 | @ConfigurationProperties("swagger.ui-config") 23 | public class SwaggerUiProperties { 24 | 25 | private String apiSorter = "alpha"; 26 | 27 | /** 28 | * 是否启用json编辑器 29 | **/ 30 | private Boolean jsonEditor = false; 31 | /** 32 | * 是否显示请求头信息 33 | **/ 34 | private Boolean showRequestHeaders = true; 35 | /** 36 | * 支持页面提交的请求类型 37 | **/ 38 | private String submitMethods = "get,post,put,delete,patch"; 39 | /** 40 | * 请求超时时间 41 | **/ 42 | private Long requestTimeout = 10000L; 43 | 44 | private Boolean deepLinking; 45 | private Boolean displayOperationId; 46 | private Integer defaultModelsExpandDepth; 47 | private Integer defaultModelExpandDepth; 48 | private ModelRendering defaultModelRendering; 49 | 50 | /** 51 | * 是否显示请求耗时,默认false 52 | */ 53 | private Boolean displayRequestDuration = true; 54 | /** 55 | * 可选 none | list 56 | */ 57 | private DocExpansion docExpansion; 58 | /** 59 | * Boolean=false OR String 60 | */ 61 | private Object filter; 62 | private Integer maxDisplayedTags; 63 | private OperationsSorter operationsSorter; 64 | private Boolean showExtensions; 65 | private TagsSorter tagsSorter; 66 | 67 | /** 68 | * Network 69 | */ 70 | private String validatorUrl; 71 | 72 | } 73 | 74 | 75 | -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/SwaggerAuthorizationConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 4 | import org.springframework.context.annotation.Configuration; 5 | import springfox.documentation.builders.PathSelectors; 6 | import springfox.documentation.service.ApiKey; 7 | import springfox.documentation.service.AuthorizationScope; 8 | import springfox.documentation.service.BasicAuth; 9 | import springfox.documentation.service.SecurityReference; 10 | import springfox.documentation.spi.service.contexts.SecurityContext; 11 | import springfox.documentation.swagger.web.ApiKeyVehicle; 12 | 13 | import java.util.Collections; 14 | import java.util.List; 15 | 16 | /** 17 | * securitySchemes 支持方式之一 ApiKey 18 | * 19 | * @author 翟永超 20 | * Create date:2020/2/2. 21 | * My blog: http://blog.didispace.com 22 | */ 23 | @Configuration 24 | @EnableConfigurationProperties(SwaggerAuthorizationProperties.class) 25 | public class SwaggerAuthorizationConfiguration { 26 | 27 | public SwaggerAuthorizationProperties swaggerAuthorizationProperties; 28 | 29 | public SwaggerAuthorizationConfiguration(SwaggerAuthorizationProperties swaggerAuthorizationProperties) { 30 | this.swaggerAuthorizationProperties = swaggerAuthorizationProperties; 31 | } 32 | 33 | /** 34 | * 配置默认的全局鉴权策略的开关,以及通过正则表达式进行匹配;默认 ^.*$ 匹配所有URL 35 | * 其中 securityReferences 为配置启用的鉴权策略 36 | * 37 | * @return 38 | */ 39 | public SecurityContext securityContext() { 40 | AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); 41 | AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; 42 | authorizationScopes[0] = authorizationScope; 43 | List defaultAuth = Collections.singletonList(SecurityReference.builder() 44 | .reference(swaggerAuthorizationProperties.getName()) 45 | .scopes(authorizationScopes).build()); 46 | 47 | return SecurityContext.builder() 48 | .securityReferences(defaultAuth) 49 | .forPaths(PathSelectors.regex(swaggerAuthorizationProperties.getAuthRegex())) 50 | .build(); 51 | } 52 | 53 | /** 54 | * 配置基于 ApiKey 的鉴权对象 55 | * 56 | * @return 57 | */ 58 | public ApiKey apiKey() { 59 | return new ApiKey(swaggerAuthorizationProperties.getName(), 60 | swaggerAuthorizationProperties.getKeyName(), 61 | ApiKeyVehicle.HEADER.getValue()); 62 | } 63 | 64 | /** 65 | * 配置基于 BasicAuth 的鉴权对象 66 | * 67 | * @return 68 | */ 69 | public BasicAuth basicAuth() { 70 | return new BasicAuth(swaggerAuthorizationProperties.getName()); 71 | } 72 | 73 | public String getType() { 74 | return swaggerAuthorizationProperties.getType(); 75 | } 76 | 77 | 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/SwaggerProperties.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | import org.springframework.boot.context.properties.ConfigurationProperties; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | /** 11 | * @author 翟永超 12 | * Create date :2017/8/7. 13 | * My blog: http://blog.didispace.com 14 | */ 15 | @Data 16 | @ConfigurationProperties("swagger") 17 | public class SwaggerProperties { 18 | 19 | /** 20 | * 标题 21 | **/ 22 | private String title = ""; 23 | /** 24 | * 描述 25 | **/ 26 | private String description = ""; 27 | /** 28 | * 版本 29 | **/ 30 | private String version = ""; 31 | /** 32 | * 许可证 33 | **/ 34 | private String license = ""; 35 | /** 36 | * 许可证URL 37 | **/ 38 | private String licenseUrl = ""; 39 | /** 40 | * 服务条款URL 41 | **/ 42 | private String termsOfServiceUrl = ""; 43 | 44 | /** 45 | * 忽略的参数类型 46 | **/ 47 | private List> ignoredParameterTypes = new ArrayList<>(); 48 | 49 | private Contact contact = new Contact(); 50 | 51 | /** 52 | * swagger会解析的包路径 53 | **/ 54 | private String basePackage = ""; 55 | 56 | /** 57 | * swagger会解析的url规则 58 | **/ 59 | private List basePath = new ArrayList<>(); 60 | /** 61 | * 在basePath基础上需要排除的url规则 62 | **/ 63 | private List excludePath = new ArrayList<>(); 64 | 65 | /** 66 | * host信息 67 | **/ 68 | private String host = ""; 69 | 70 | /** 71 | * 全局参数配置 72 | **/ 73 | private List globalOperationParameters; 74 | 75 | /** 76 | * 是否使用默认预定义的响应消息 ,默认 true 77 | **/ 78 | private Boolean applyDefaultResponseMessages = true; 79 | 80 | /** 81 | * 全局响应消息 82 | **/ 83 | private GlobalResponseMessage globalResponseMessage; 84 | 85 | @Data 86 | @NoArgsConstructor 87 | public static class GlobalOperationParameter { 88 | /** 89 | * 参数名 90 | **/ 91 | private String name; 92 | 93 | /** 94 | * 描述信息 95 | **/ 96 | private String description; 97 | 98 | /** 99 | * 指定参数类型 100 | **/ 101 | private String modelRef; 102 | 103 | /** 104 | * 参数放在哪个地方:header,query,path,formData,cookie,form 105 | **/ 106 | private String parameterType; 107 | 108 | /** 109 | * 参数是否必须传 110 | **/ 111 | private Boolean required; 112 | 113 | } 114 | 115 | @Data 116 | @NoArgsConstructor 117 | public static class Contact { 118 | 119 | /** 120 | * 联系人 121 | **/ 122 | private String name = ""; 123 | /** 124 | * 联系人url 125 | **/ 126 | private String url = ""; 127 | /** 128 | * 联系人email 129 | **/ 130 | private String email = ""; 131 | 132 | } 133 | 134 | @Data 135 | @NoArgsConstructor 136 | public static class GlobalResponseMessage { 137 | 138 | /** 139 | * POST 响应消息体 140 | **/ 141 | List post = new ArrayList<>(); 142 | 143 | /** 144 | * GET 响应消息体 145 | **/ 146 | List get = new ArrayList<>(); 147 | 148 | /** 149 | * PUT 响应消息体 150 | **/ 151 | List put = new ArrayList<>(); 152 | 153 | /** 154 | * PATCH 响应消息体 155 | **/ 156 | List patch = new ArrayList<>(); 157 | 158 | /** 159 | * DELETE 响应消息体 160 | **/ 161 | List delete = new ArrayList<>(); 162 | 163 | /** 164 | * HEAD 响应消息体 165 | **/ 166 | List head = new ArrayList<>(); 167 | 168 | /** 169 | * OPTIONS 响应消息体 170 | **/ 171 | List options = new ArrayList<>(); 172 | 173 | /** 174 | * TRACE 响应消息体 175 | **/ 176 | List trace = new ArrayList<>(); 177 | 178 | } 179 | 180 | @Data 181 | @NoArgsConstructor 182 | public static class GlobalResponseMessageBody { 183 | 184 | /** 185 | * 响应码 186 | **/ 187 | private String code; 188 | 189 | /** 190 | * 响应消息 191 | **/ 192 | private String description; 193 | 194 | private String representation; 195 | 196 | /** 197 | * 响应体 198 | **/ 199 | private String modelRef; 200 | 201 | } 202 | 203 | 204 | } 205 | 206 | 207 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.spring4all 8 | swagger-spring-boot-starter 9 | 2.0.0-SNAPSHOT 10 | 11 | spring-boot-starter-swagger 12 | https://github.com/SpringForAll/spring-boot-starter-swagger 13 | starter for swagger2 14 | 15 | 16 | org.sonatype.oss 17 | oss-parent 18 | 7 19 | 20 | 21 | 22 | 23 | The Apache Software License, Version 2.0 24 | http://www.apache.org/licenses/LICENSE-2.0.txt 25 | repo 26 | 27 | 28 | 29 | 30 | http://spring4all.com 31 | git@github.com:SpringForAll/spring-boot-starter-swagger.git 32 | https://github.com/SpringForAll/spring-boot-starter-swagger 33 | 34 | 35 | 36 | 37 | 程序猿DD 38 | dyc87112@qq.com 39 | http://didispace.com 40 | 41 | 42 | 小火 43 | xiaohuo200@gmail.com 44 | https://renlulu.github.io/ 45 | 46 | 47 | 48 | 49 | UTF-8 50 | 1.8 51 | 2.3.0.RELEASE 52 | 3.0.0 53 | 1.5.24 54 | 1.18.6 55 | 56 | 57 | 58 | 59 | org.springframework.boot 60 | spring-boot-starter 61 | true 62 | 63 | 64 | org.springframework.boot 65 | spring-boot-configuration-processor 66 | true 67 | 68 | 69 | org.springframework.boot 70 | spring-boot-starter-web 71 | true 72 | 73 | 74 | org.springframework.boot 75 | spring-boot-starter-webflux 76 | true 77 | 78 | 79 | 80 | io.springfox 81 | springfox-boot-starter 82 | ${version.swagger} 83 | 84 | 85 | 86 | io.swagger 87 | swagger-models 88 | ${version.swagger-models} 89 | 90 | 91 | 92 | org.projectlombok 93 | lombok 94 | ${version.lombok} 95 | provided 96 | 97 | 98 | 99 | com.google.guava 100 | guava 101 | 30.0-jre 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | org.springframework.boot 110 | spring-boot-dependencies 111 | ${version.spring-boot} 112 | pom 113 | import 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | org.apache.maven.plugins 122 | maven-compiler-plugin 123 | 3.3 124 | 125 | ${project.build.sourceEncoding} 126 | ${version.java} 127 | ${version.java} 128 | true 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | jcenter-snapshots 137 | jcenter 138 | https://jcenter.bintray.com/ 139 | 140 | 141 | -------------------------------------------------------------------------------- /src/main/java/com/spring4all/swagger/DocketConfiguration.java: -------------------------------------------------------------------------------- 1 | package com.spring4all.swagger; 2 | 3 | import com.google.common.base.Predicates; 4 | import lombok.RequiredArgsConstructor; 5 | import org.springframework.context.annotation.Bean; 6 | import org.springframework.context.annotation.Configuration; 7 | import springfox.documentation.builders.ApiInfoBuilder; 8 | import springfox.documentation.builders.RequestHandlerSelectors; 9 | import springfox.documentation.builders.RequestParameterBuilder; 10 | import springfox.documentation.schema.ScalarType; 11 | import springfox.documentation.service.ApiInfo; 12 | import springfox.documentation.service.Contact; 13 | import springfox.documentation.service.RequestParameter; 14 | import springfox.documentation.spi.DocumentationType; 15 | import springfox.documentation.spring.web.plugins.Docket; 16 | 17 | import java.util.ArrayList; 18 | import java.util.Collections; 19 | import java.util.List; 20 | import java.util.function.Predicate; 21 | import java.util.stream.Collectors; 22 | 23 | import static java.util.Collections.singletonList; 24 | 25 | /** 26 | * @author 翟永超 27 | * Create date:2017/8/7. 28 | * My blog: http://blog.didispace.com 29 | */ 30 | @Configuration 31 | public class DocketConfiguration { 32 | 33 | private SwaggerProperties swaggerProperties; 34 | private SwaggerAuthorizationConfiguration swaggerAuthorizationConfiguration; 35 | 36 | public DocketConfiguration(SwaggerProperties swaggerProperties, 37 | SwaggerAuthorizationConfiguration swaggerAuthorizationConfiguration) { 38 | this.swaggerProperties = swaggerProperties; 39 | this.swaggerAuthorizationConfiguration = swaggerAuthorizationConfiguration; 40 | } 41 | 42 | @Bean 43 | public Docket createRestApi() { 44 | // 文档的基础信息配置 45 | Docket builder = new Docket(DocumentationType.SWAGGER_2) 46 | .host(swaggerProperties.getHost()) 47 | .apiInfo(apiInfo(swaggerProperties)); 48 | 49 | // 安全相关的配置 50 | builder.securityContexts(Collections.singletonList(swaggerAuthorizationConfiguration.securityContext())); 51 | if ("BasicAuth".equalsIgnoreCase(swaggerAuthorizationConfiguration.getType())) { 52 | builder.securitySchemes(Collections.singletonList(swaggerAuthorizationConfiguration.basicAuth())); 53 | } else if (!"None".equalsIgnoreCase(swaggerAuthorizationConfiguration.getType())) { 54 | builder.securitySchemes(Collections.singletonList(swaggerAuthorizationConfiguration.apiKey())); 55 | } 56 | 57 | // 要忽略的参数类型 58 | Class[] array = new Class[swaggerProperties.getIgnoredParameterTypes().size()]; 59 | Class[] ignoredParameterTypes = swaggerProperties.getIgnoredParameterTypes().toArray(array); 60 | builder.ignoredParameterTypes(ignoredParameterTypes); 61 | 62 | // 设置全局参数 63 | if (swaggerProperties.getGlobalOperationParameters() != null) { 64 | builder.globalRequestParameters(globalRequestParameters(swaggerProperties)); 65 | } 66 | 67 | // 需要生成文档的接口目标配置 68 | Docket docket = builder.select() 69 | // 通过扫描包选择接口 70 | .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage())) 71 | // 通过路径匹配选择接口 72 | .paths(paths(swaggerProperties)) 73 | .build(); 74 | 75 | return docket; 76 | } 77 | 78 | /** 79 | * 全局请求参数 80 | * 81 | * @param swaggerProperties {@link SwaggerProperties} 82 | * @return RequestParameter {@link RequestParameter} 83 | */ 84 | private List globalRequestParameters(SwaggerProperties swaggerProperties) { 85 | return swaggerProperties.getGlobalOperationParameters().stream().map(param -> new RequestParameterBuilder() 86 | .name(param.getName()) 87 | .description(param.getDescription()) 88 | .in(param.getParameterType()) 89 | .required(param.getRequired()) 90 | .query(q -> q.defaultValue(param.getModelRef())) 91 | .query(q -> q.model(m -> m.scalarModel(ScalarType.STRING))) 92 | .build()).collect(Collectors.toList()); 93 | } 94 | 95 | /** 96 | * API接口路径选择 97 | * 98 | * @param swaggerProperties 99 | * @return 100 | */ 101 | 102 | private Predicate paths(SwaggerProperties swaggerProperties) { 103 | // base-path处理 104 | // 当没有配置任何path的时候,解析/** 105 | if (swaggerProperties.getBasePath().isEmpty()) { 106 | swaggerProperties.getBasePath().add("/**"); 107 | } 108 | List> basePath = new ArrayList<>(); 109 | for (String path : swaggerProperties.getBasePath()) { 110 | basePath.add(PathSelectors.ant(path)); 111 | } 112 | 113 | // exclude-path处理 114 | List> excludePath = new ArrayList<>(); 115 | for (String path : swaggerProperties.getExcludePath()) { 116 | excludePath.add(PathSelectors.ant(path)); 117 | } 118 | 119 | return Predicates.and( 120 | Predicates.not(Predicates.or(excludePath)), 121 | Predicates.or(basePath) 122 | ); 123 | } 124 | 125 | /** 126 | * API文档基本信息 127 | * 128 | * @param swaggerProperties 129 | * @return 130 | */ 131 | private ApiInfo apiInfo(SwaggerProperties swaggerProperties) { 132 | ApiInfo apiInfo = new ApiInfoBuilder() 133 | .title(swaggerProperties.getTitle()) 134 | .description(swaggerProperties.getDescription()) 135 | .version(swaggerProperties.getVersion()) 136 | .license(swaggerProperties.getLicense()) 137 | .licenseUrl(swaggerProperties.getLicenseUrl()) 138 | .contact(new Contact(swaggerProperties.getContact().getName(), 139 | swaggerProperties.getContact().getUrl(), 140 | swaggerProperties.getContact().getEmail())) 141 | .termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()) 142 | .build(); 143 | return apiInfo; 144 | } 145 | 146 | 147 | } 148 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 简介 2 | 3 | 该项目主要利用Spring Boot的自动化配置特性来实现快速的将swagger2引入spring boot应用来生成API文档,简化原生使用swagger2的整合代码。 4 | 5 | - 源码地址 6 | - GitHub:https://github.com/dyc87112/spring-boot-starter-swagger 7 | - 码云:https://gitee.com/didispace/spring-boot-starter-swagger 8 | - 使用样例:https://github.com/dyc87112/swagger-starter-demo 9 | - 我的博客:http://blog.didispace.com 10 | - 我们社区:http://www.spring4all.com 11 | 12 | **小工具一枚,欢迎使用和Star支持,如使用过程中碰到问题,可以提出Issue,我会尽力完善该Starter** 13 | 14 | # 版本基础 15 | 16 | - Swagger:2.9.2 17 | 18 | # 如何使用 19 | 20 | 在该项目的帮助下,我们的Spring Boot可以轻松的引入swagger2,主需要做下面两个步骤: 21 | 22 | - 在`pom.xml`中引入依赖: 23 | 24 | ```xml 25 | 26 | com.spring4all 27 | swagger-spring-boot-starter 28 | 1.9.1.RELEASE 29 | 30 | ``` 31 | 32 | **注意:从`1.6.0`开始,我们按Spring Boot官方建议修改了artifactId为`swagger-spring-boot-starter`,1.6.0之前的版本不做修改,依然为使用`spring-boot-starter-swagger` !** 33 | 34 | - 在应用主类中增加`@EnableSwagger2Doc`注解 35 | 36 | ```java 37 | @EnableSwagger2Doc 38 | @SpringBootApplication 39 | public class Bootstrap { 40 | 41 | public static void main(String[] args) { 42 | SpringApplication.run(Bootstrap.class, args); 43 | } 44 | 45 | } 46 | ``` 47 | 48 | 默认情况下就能产生所有当前Spring MVC加载的请求映射文档。 49 | 50 | # 参数配置 51 | 52 | 更细致的配置内容参考如下: 53 | 54 | ## 配置示例 55 | 56 | ```properties 57 | swagger.enabled=true 58 | 59 | swagger.title=spring-boot-starter-swagger 60 | swagger.description=Starter for swagger 2.x 61 | swagger.version=1.4.0.RELEASE 62 | swagger.license=Apache License, Version 2.0 63 | swagger.licenseUrl=https://www.apache.org/licenses/LICENSE-2.0.html 64 | swagger.termsOfServiceUrl=https://github.com/dyc87112/spring-boot-starter-swagger 65 | swagger.contact.name=didi 66 | swagger.contact.url=http://blog.didispace.com 67 | swagger.contact.email=dyc87112@qq.com 68 | swagger.base-package=com.didispace 69 | swagger.base-path=/** 70 | swagger.exclude-path=/error, /ops/** 71 | 72 | swagger.globalOperationParameters[0].name=name one 73 | swagger.globalOperationParameters[0].description=some description one 74 | swagger.globalOperationParameters[0].modelRef=string 75 | swagger.globalOperationParameters[0].parameterType=header 76 | swagger.globalOperationParameters[0].required=true 77 | swagger.globalOperationParameters[1].name=name two 78 | swagger.globalOperationParameters[1].description=some description two 79 | swagger.globalOperationParameters[1].modelRef=string 80 | swagger.globalOperationParameters[1].parameterType=body 81 | swagger.globalOperationParameters[1].required=false 82 | 83 | // 取消使用默认预定义的响应消息,并使用自定义响应消息 84 | swagger.apply-default-response-messages=false 85 | swagger.global-response-message.get[0].code=401 86 | swagger.global-response-message.get[0].message=401get 87 | swagger.global-response-message.get[1].code=500 88 | swagger.global-response-message.get[1].message=500get 89 | swagger.global-response-message.get[1].modelRef=ERROR 90 | swagger.global-response-message.post[0].code=500 91 | swagger.global-response-message.post[0].message=500post 92 | swagger.global-response-message.post[0].modelRef=ERROR 93 | ``` 94 | 95 | ## 配置说明 96 | 97 | ### 默认配置 98 | 99 | ```properties 100 | - swagger.enabled=是否启用swagger,默认:true 101 | - swagger.title=标题 102 | - swagger.description=描述 103 | - swagger.version=版本 104 | - swagger.license=许可证 105 | - swagger.licenseUrl=许可证URL 106 | - swagger.termsOfServiceUrl=服务条款URL 107 | - swagger.contact.name=维护人 108 | - swagger.contact.url=维护人URL 109 | - swagger.contact.email=维护人email 110 | - swagger.base-package=swagger扫描的基础包,默认:全扫描 111 | - swagger.base-path=需要处理的基础URL规则,默认:/** 112 | - swagger.exclude-path=需要排除的URL规则,默认:空 113 | - swagger.host=文档的host信息,默认:空 114 | - swagger.globalOperationParameters[0].name=参数名 115 | - swagger.globalOperationParameters[0].description=描述信息 116 | - swagger.globalOperationParameters[0].modelRef=指定参数类型 117 | - swagger.globalOperationParameters[0].parameterType=指定参数存放位置,可选header,query,path,body.form 118 | - swagger.globalOperationParameters[0].required=指定参数是否必传,true,false 119 | ``` 120 | 121 | 122 | > `1.3.0.RELEASE`新增:`swagger.host`属性,同时也支持指定docket的配置 123 | > 124 | > `1.4.0.RELEASE`新增: 125 | > - `swagger.enabled`:用于开关swagger的配置 126 | > - `swagger.globalOperationParameters`:用于设置全局的参数,比如:header部分的accessToken等。该参数支持指定docket的配置。 127 | 128 | ### Path规则说明 129 | 130 | `swagger.base-path`和`swagger.exclude-path`使用ANT规则配置。 131 | 132 | 我们可以使用`swagger.base-path`来指定所有需要生成文档的请求路径基础规则,然后再利用`swagger.exclude-path`来剔除部分我们不需要的。 133 | 134 | 比如,通常我们可以这样设置: 135 | 136 | ```properties 137 | management.context-path=/ops 138 | 139 | swagger.base-path=/** 140 | swagger.exclude-path=/ops/**, /error 141 | ``` 142 | 143 | 上面的设置将解析所有除了`/ops/`开始以及spring boot自带`/error`请求路径。 144 | 145 | 其中,`exclude-path`可以配合`management.context-path=/ops`设置的spring boot actuator的context-path来排除所有监控端点。 146 | 147 | ### 分组配置 148 | 149 | 当我们一个项目的API非常多的时候,我们希望对API文档实现分组。从1.2.0.RELEASE开始,将支持分组配置功能。 150 | 151 | ![分组功能](https://github.com/dyc87112/spring-boot-starter-swagger/blob/master/images/swagger-group.png) 152 | 153 | 具体配置内容如下: 154 | 155 | ```properties 156 | - swagger.docket..title=标题 157 | - swagger.docket..description=描述 158 | - swagger.docket..version=版本 159 | - swagger.docket..license=许可证 160 | - swagger.docket..licenseUrl=许可证URL 161 | - swagger.docket..termsOfServiceUrl=服务条款URL 162 | - swagger.docket..contact.name=维护人 163 | - swagger.docket..contact.url=维护人URL 164 | - swagger.docket..contact.email=维护人email 165 | - swagger.docket..base-package=swagger扫描的基础包,默认:全扫描 166 | - swagger.docket..base-path=需要处理的基础URL规则,默认:/** 167 | - swagger.docket..exclude-path=需要排除的URL规则,默认:空 168 | - swagger.docket..name=参数名 169 | - swagger.docket..modelRef=指定参数类型 170 | - swagger.docket..parameterType=指定参数存放位置,可选header,query,path,body.form 171 | - swagger.docket..required=true=指定参数是否必传,true,false 172 | - swagger.docket..globalOperationParameters[0].name=参数名 173 | - swagger.docket..globalOperationParameters[0].description=描述信息 174 | - swagger.docket..globalOperationParameters[0].modelRef=指定参数存放位置,可选header,query,path,body.form 175 | - swagger.docket..globalOperationParameters[0].parameterType=指定参数是否必传,true,false 176 | ``` 177 | 178 | 说明:``为swagger文档的分组名称,同一个项目中可以配置多个分组,用来划分不同的API文档。 179 | 180 | 181 | **分组配置示例** 182 | 183 | ```properties 184 | swagger.docket.aaa.title=group-a 185 | swagger.docket.aaa.description=Starter for swagger 2.x 186 | swagger.docket.aaa.version=1.3.0.RELEASE 187 | swagger.docket.aaa.termsOfServiceUrl=https://gitee.com/didispace/spring-boot-starter-swagger 188 | swagger.docket.aaa.contact.name=zhaiyongchao 189 | swagger.docket.aaa.contact.url=http://spring4all.com/ 190 | swagger.docket.aaa.contact.email=didi@potatomato.club 191 | swagger.docket.aaa.excludePath=/ops/** 192 | swagger.docket.aaa.globalOperationParameters[0].name=name three 193 | swagger.docket.aaa.globalOperationParameters[0].description=some description three override 194 | swagger.docket.aaa.globalOperationParameters[0].modelRef=string 195 | swagger.docket.aaa.globalOperationParameters[0].parameterType=header 196 | 197 | swagger.docket.bbb.title=group-bbb 198 | swagger.docket.bbb.basePackage=com.yonghui 199 | ``` 200 | 201 | 说明:默认配置与分组配置可以一起使用。在分组配置中没有配置的内容将使用默认配置替代,所以默认配置可以作为分组配置公共部分属性的配置。`swagger.docket.aaa.globalOperationParameters[0].name`会覆盖同名的全局配置。 202 | 203 | ### JSR-303校验注解支持(1.5.0 + 支持) 204 | 205 | 支持对JSR-303校验注解的展示,如下图所示: 206 | 207 | ![JSR-303校验展示](https://github.com/dyc87112/spring-boot-starter-swagger/blob/master/images/jsr-303.png) 208 | 209 | 目前共支持以下几个注解: 210 | 211 | - `@NotNull` 212 | - `@Max、@Min` 213 | - `@Size` 214 | - `@Pattern` 215 | 216 | ### 自定义全局响应消息配置(1.6.0 + 支持) 217 | 218 | 支持 POST,GET,PUT,PATCH,DELETE,HEAD,OPTIONS,TRACE 全局响应消息配置,配置如下 219 | 220 | ```properties 221 | // 取消使用默认预定义的响应消息,并使用自定义响应消息 222 | swagger.apply-default-response-messages=false 223 | swagger.global-response-message.get[0].code=401 224 | swagger.global-response-message.get[0].message=401get 225 | swagger.global-response-message.get[1].code=500 226 | swagger.global-response-message.get[1].message=500get 227 | swagger.global-response-message.get[1].modelRef=ERROR 228 | swagger.global-response-message.post[0].code=500 229 | swagger.global-response-message.post[0].message=500post 230 | swagger.global-response-message.post[0].modelRef=ERROR 231 | ``` 232 | 233 | ### UI功能配置(1.6.0 + 支持) 234 | 235 | - 调试按钮的控制(try it out) 236 | 237 | ```properties 238 | swagger.ui-config.submit-methods=get,delete 239 | ``` 240 | 241 | 该参数值为提供调试按钮的HTTP请求类型,多个用,分割。 242 | 243 | 如果不想开启调试功能,只需要如下设置即可: 244 | 245 | ```properties 246 | swagger.ui-config.submit-methods= 247 | ``` 248 | 249 | - 其他配置 250 | 251 | ```properties 252 | # json编辑器 253 | swagger.ui-config.json-editor=false 254 | 255 | # 显示请求头 256 | swagger.ui-config.show-request-headers=true 257 | 258 | # 页面调试请求的超时时间 259 | swagger.ui-config.request-timeout=5000 260 | ``` 261 | 262 | ### ignoredParameterTypes配置(1.6.0 + 支持) 263 | 264 | ```properties 265 | # 基础配置 266 | swagger.ignored-parameter-types[0]=com.didispace.demo.User 267 | swagger.ignored-parameter-types[1]=com.didispace.demo.Product 268 | 269 | # 分组配置 270 | swagger.docket.aaa.ignored-parameter-types[0]=com.didispace.demo.User 271 | swagger.docket.aaa.ignored-parameter-types[1]=com.didispace.demo.Product 272 | ``` 273 | 274 | > 该参数作用: 275 | > Q. Infinite loop when springfox tries to determine schema for objects with nested/complex constraints? 276 | > A. If you have recursively defined objects, I would try and see if providing an alternate type might work or perhaps even ignoring the offending classes e.g. order using the docket. ignoredParameterTypes(Order.class). This is usually found in Hibernate domain objects that have bidirectional dependencies on other objects. 277 | 278 | ### Authorization 鉴权配置 (1.7.0 + 支持) 279 | 280 | - 新增 Authorization 配置项 281 | 282 | ```properties 283 | # 鉴权策略ID,对应 SecurityReferences ID 284 | swagger.authorization.name=Authorization 285 | 286 | # 鉴权策略,可选 ApiKey | BasicAuth | None,默认ApiKey 287 | swagger.authorization.type=ApiKey 288 | 289 | # 鉴权传递的Header参数 290 | swagger.authorization.key-name=token 291 | 292 | # 需要开启鉴权URL的正则, 默认^.*$匹配所有URL 293 | swagger.authorization.auth-regex=^.*$ 294 | ``` 295 | 296 | 备注:目前支持`ApiKey` | `BasicAuth`鉴权模式,`None`除消鉴权模式,默认ApiKey,后续添加`Oauth2`支持 297 | 298 | **使用须知** 299 | 300 | > 1. 默认已经在全局开启了`global`的SecurityReferences,无需配置任何参数就可以使用; 301 | > 2. 全局鉴权的范围在可以通过以上参数`auth-regex`进行正则表达式匹配控制; 302 | > 3. 除了全局开启外,还可以手动通过注解在RestController上进行定义鉴权,使用方式如下: 303 | 304 | ```java 305 | // 其中的ID Authorization 即为配置项 swagger.authorization.name,详细请关注后面的配置代码 306 | @ApiOperation(value = "Hello World", authorizations = {@Authorization(value = "Authorization")}) 307 | @RequestMapping(value = "/hello", method = RequestMethod.GET) 308 | String hello(); 309 | ``` 310 | 311 | **关于如何配置实现鉴权,请关注以下code:** 312 | 313 | ```java 314 | /** 315 | * 配置基于 ApiKey 的鉴权对象 316 | * 317 | * @return 318 | */ 319 | private ApiKey apiKey() { 320 | return new ApiKey(swaggerProperties().getAuthorization().getName(), 321 | swaggerProperties().getAuthorization().getKeyName(), 322 | ApiKeyVehicle.HEADER.getValue()); 323 | } 324 | 325 | /** 326 | * 配置默认的全局鉴权策略的开关,以及通过正则表达式进行匹配;默认 ^.*$ 匹配所有URL 327 | * 其中 securityReferences 为配置启用的鉴权策略 328 | * 329 | * @return 330 | */ 331 | private SecurityContext securityContext() { 332 | return SecurityContext.builder() 333 | .securityReferences(defaultAuth()) 334 | .forPaths(PathSelectors.regex(swaggerProperties().getAuthorization().getAuthRegex())) 335 | .build(); 336 | } 337 | 338 | /** 339 | * 配置默认的全局鉴权策略;其中返回的 SecurityReference 中,reference 即为ApiKey对象里面的name,保持一致才能开启全局鉴权 340 | * 341 | * @return 342 | */ 343 | private List defaultAuth() { 344 | AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); 345 | AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; 346 | authorizationScopes[0] = authorizationScope; 347 | return Collections.singletonList(SecurityReference.builder() 348 | .reference(swaggerProperties().getAuthorization().getName()) 349 | .scopes(authorizationScopes).build()); 350 | } 351 | ``` 352 | 353 | ## 贡献者 354 | 355 | - [程序猿DD-翟永超](https://github.com/dyc87112/) 356 | - [小火](https://renlulu.github.io/) 357 | - [泥瓦匠BYSocket](https://github.com/JeffLi1993) 358 | - [LarryKoo-古拉里](https://github.com/gumutianqi) 359 | --------------------------------------------------------------------------------