1、引入swagger的jar包
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.1</version>
</dependency>
注:这里重新引入swagger-models-1.6.1版本,是因为springfox-swagger2-2.9.2版本引入的swagger-models版本较低,当打开swagger-ui.html的时候,控制台会看到莫名其妙的类型错误
2、启用swagger配置
@Configuration
@EnableSwagger2
public class Swagger2Configuration extends WebMvcConfigurationSupport {
@Conditional(Swagger2EnableCondition.class)
@Bean
public Docket createSwaggerApiUi() {
/*
* swagger2 ui api 基础信息
*/
ApiInfo apiInfo = new ApiInfoBuilder()
.title("title")
.description("description")
.version("1.0.0")
.build();
// 启用ui api文档
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo).select()
//swagger要扫描的包
.apis(RequestHandlerSelectors.basePackage("com.zhoulp"))
.paths(PathSelectors.any())
.build();
}
@Conditional(Swagger2EnableCondition.class)
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 解决静态资源无法访问
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
// 解决swagger无法访问
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
// 解决swagger的js文件无法访问
registry.addResourceHandler("/webjars/springfox-swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
注意:建议把 registry.addResourceHandler("/webjars/springfox-swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
换为registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");,以防部分环境打开swagger-ui.html
页面空白,报js、css找不到之类的
3、控制开发、测试环境才开启
public class Swagger2EnableCondition implements Condition {
private static final String[] ENABLE_PROFILE = {"local", "deve", "test"};
/*
* 根据启动环境参数判断是否开启swagger2页面api文档
* 开发、测试开启;生产关闭
*/
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String[] profiles = context.getEnvironment().getActiveProfiles();
if(profiles == null || profiles.length == 0){
return true;
}
String[] swaggerProfiles = context.getEnvironment().getProperty("swagger2.api.ui.enableProfile", String[].class);
if(swaggerProfiles == null || swaggerProfiles.length == 0){
swaggerProfiles = ENABLE_PROFILE;
}
boolean enable = false;
for(String tmp1 : swaggerProfiles) {
for (String tmp2 : profiles) {
if (tmp2.equals(tmp1)) {
enable = true;
}
}
}
return enable;
}
}
来源:oschina
链接:https://my.oschina.net/u/4198095/blog/4328007