思路:
配置文件区分添加开启与关闭标识,然后swagger读取boolean值,然后添加判断设置即可。
配置demo如下:
- pom.xml
<!--swagger start-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
- 属性配置文件
application-dev.properties 文件:
swagger.show=true
application-prod.properties 文件:
swagger.show=false
- 代码
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* Created by LT on 2019/4.05
*
* 访问路径:http://192.168.1.89:8080/demo(项目名称)/swagger-ui.html
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig{
@Value("${swagger.show}")
private boolean swaggerShow;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.demo.bi.controller"))
// 如果是线上环境,添加路径过滤,设置为全部都不符合
.paths(swaggerShow==true?PathSelectors.any():PathSelectors.none())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("接口api")
.description("内部接口api文档")
.contact("LT")
.version("1.0")
.build();
}
}