io.springfox
springfox-swagger2
2.7.0
com.github.xiaoymin
swagger-bootstrap-ui
1.9.6
SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// 扫描有哪些包下生成 Swagger文档
@Bean
public Docket createRestApi(){
return new Docket(documentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.abin.controller"))
.paths(PathSelectors.any())
.build();
}
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("云e办接口文档")
.description("云e办接口文档")
.contact(new Contact("crabin" , "http://localhost:8088/doc.html","1528392308@qq.com"))
.version("1.0")
.build();
}
}
导入版本正确可以,加入报错:Failed to start bean ‘documentationPluginsBootstrapper‘; nested exception is
可能是因为Springboot版本太高导致的
两种解决方法:
1.编写 WebMvcConfigurer 配置类
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**").addResourceLocations(
"classpath:/static/");
registry.addResourceHandler("swagger-ui.html", "doc.html").addResourceLocations(
"classpath:/meta-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations(
"classpath:/meta-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
2.在 application.yaml 中:
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
访问:http://localhost:8088/doc.html
调试:
在createRestApi()方法后面继续 设置权限:
.securityContexts(securityContexts())
.securitySchemes(securitySchemes());
@Configuration
@EnableSwagger2
public class SwaggerConfig {
// 扫描有哪些包下生成 Swagger文档
@Bean
public Docket createRestApi(){
return new Docket(documentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.abin.controller"))
.paths(PathSelectors.any())
.build()
.securityContexts(securityContexts())
.securitySchemes(securitySchemes());
}
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("云e办接口文档")
.description("云e办接口文档")
.contact(new Contact("crabin" , "http://localhost:8088/doc.html","1528392308@qq.com"))
.version("1.0")
.build();
}
private List securitySchemes() {
// 设置请求头
List result = new ArrayList<>();
ApiKey apiKey = new ApiKey("Authorization", "Authorization", "Header");
result.add(apiKey);
return result;
}
private List securityContexts() {
// 设置需要登录认证的路径
List result = new ArrayList<>();
result.add(getContextByPath("/hello/.*"));
return result;
}
private SecurityContext getContextByPath(String pathRegex) {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex(pathRegex))
.build();
}
private List defaultAuth() {
List result = new ArrayList<>();
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
result.add(new SecurityReference("Authorization", authorizationScopes));
return result;
}
}



