经常使用swagger-ui 想着方便就放出来在csdn备份一下。以下代码
首先引入swagger 的pom 文件 我用的2.9.2 的文件,引入即可集成 swagger,不需要引入很多。
<swagger.version>2.9.2</swagger.version>
<!--swagger-->
<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>
引入了pom之后,配置swagger的策略 配置类
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Value("${swagger.auth}")
private String swaggerAuth;
@Value("${swagger.api.version}")
private String apiVersion;
@Value("${swagger.title}")
private String swaggerTitle;
@Value("${swagger.description}")
private String description;
@Bean
public Docket createRestApi() {
// return new Docket(DocumentationType.SWAGGER_2)
// .apiInfo(apiInfo())
// .select()
// .apis(RequestHandlerSelectors.basePackage("com.iskSmart.root.custom"))
// .paths(PathSelectors.any())
// .build();
return new Docket(DocumentationType.SWAGGER_2).
useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.regex("^(?!auth).*$"))
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title(swaggerTitle)
.description(description)
// .termsOfServiceUrl("http://www.baidu.com/")
.contact(swaggerAuth)
.version(apiVersion)
.build();
}
private List<ApiKey> securitySchemes() {
List<ApiKey> apiKeyList= new ArrayList<ApiKey>();
apiKeyList.add(new ApiKey("token", "token", "header"));
return apiKeyList;
}
private List<SecurityContext> securityContexts() {
return newArrayList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build()
);
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(
new SecurityReference("Authorization", authorizationScopes)
);
}
// private List<Parameter> setHeaderToken() {
// ParameterBuilder tokenPar = new ParameterBuilder();
// List<Parameter> pars = new ArrayList<>();
// tokenPar.name("X-Auth-Token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
// pars.add(tokenPar.build());
// return pars;
// }
}
配置之后,就已经集成了 swagger了 若还未生效 在 主函数启动了 配置
@EnableSwagger2
注解