问题描述:
项目整合了Swagger2,想弄一个开关,在本地开发阶段:
可以通过 http://localhost:8080swagger-ui.html 调试接口;测试,正式环境不可访问;
解决方案:
使用spring boot 的:@ConditionalOnProperty标签可以控制被@Configuration注释的配置类 是否生效
具体代码:
@Configuration
@ConditionalOnProperty(prefix = "swagger", value = {"enable"}, havingValue = "true")
@EnableSwagger2
public class SwaggerConfig {}
-
以下代码为ConditionalOnProperty注解的属性说明: @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) @Documented @Conditional(OnPropertyCondition.class) public @interface ConditionalOnProperty { //在application.properties中自定义属性的名称:例如enable String[] value() default {}; //在application.properties中自定义属性的前缀:例如swagger; 可以拼接value和name配置的值 String prefix() default ""; //在application.properties中自定义属性的全称:例如swagger.enable或者enable String[] name() default {}; //用来在application.properties中自定义属性的值进行比较,若想同:则Configuration配置类生效,反之不生效; String havingValue() default ""; boolean matchIfMissing() default false; boolean relaxedNames() default true; } - application.properties中添加对应配置:
#swagger开关: true 打开,false 关闭 swagger.enable = true
- 三种配置效果想同:
-
@ConditionalOnProperty(prefix = "swagger",name = {"enable"},havingValue = "true") -
@ConditionalOnProperty(name = {"swagger.enable"},havingValue = "true") -
@ConditionalOnProperty(prefix = "swagger",value = {"enable"},havingValue = "true")
知识笔记!有不对的地方,欢迎指正!
本文介绍如何在SpringBoot项目中使用@ConditionalOnProperty控制Swagger2的开关,实现仅在本地开发环境下启用Swagger UI,而在测试和正式环境中禁用的功能。
1232

被折叠的 条评论
为什么被折叠?



