在使用spring-boot开发的时候,我们很多时候会使用swagger作为api文档输出。可以在UI界面上看到api的路径,参数等等。
当然,作为开发环境是很方便的,但是上生产环境的时候,我们需要把swagger禁掉。怎么通过配置文件的方法来禁用swagger呢?
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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;
/**
* swagger 配置文件
* @author cdj
* @date 2018年7月23日 上午8:51:08
*/
@Configuration
@ConditionalOnProperty(prefix = "swagger",value = {"enable"},havingValue = "true")
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.edgecdj"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2构建RESTful APIs")
.description("支付相关demo")
.termsOfServiceUrl("www.baidu.com")
.contact("支付相关demo")
.version("1.0")
.build();
}
}
添加注解
@ConditionalOnProperty(prefix = "swagger",value = {"enable"},havingValue = "true")
然后再配置文件中加入 swagger.enable=true
true为开启,false或没有为关闭。
关键就是这里的 @ConditionalOnProperty
这里的属性key是 swagger.enable ,havingValue 是期望值,只有在值等于期望值的时候,才会生效。也就是说,swagger.enable只能为true的时候才会生效,其他值或不设值,都不会生效的。