ConditionalOnProperty配置swagger不生效问题及解决

网友投稿 717 2022-07-23


目录ConditionalOnProperty配置swagger不生效问题问题原因解决方案@ConditionalOnProperty理解和使用注解源码属性值不是boolean类型的情况属性值为boolean类型

ConditionalOnProperty配置swagger不生效

问题

在正式环境准备关闭Swagger,添加了ConditionalOnProperty注解进行配置,结果发现怎么也无法关闭swagger。

问题原因

@EnableSwagger2在多个地方进行了配置,如下:

1)应用程序处进行了配置

@SpringCloudApplication

@EnableSwagger2 //在应用程序处进行了配置

public class SysApplication {

public static void main(String[] args) {

SpringApplication.run(SysApplication.class,args);

}

}

2)swagger处进行了配置

@Configuration

@EnableSwagger2 //在swagger本身配置处进行了配置

@ConditionalOnProperty(value = "swagger.manenabled", havingValue = "true")

public class SwaggerConfig {

}

实际在2)处的配置已经生效,但由于1)处有配置所以造成这个问题。

解决方案

将1)处的配置关闭即可。

@ConditionalOnProperty理解和使用

在Spring应用程序开发的过程中,可能需要根据配置属性的存在和值有条件地创建一些bean,@ConditionalOnProperty注解用于仅在环境属性存在且具有特定值时才启用 bean 注册。

注解源码

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.TYPE, ElementType.METHOD})

@Documented

@Conditional({OnPropertyCondition.class})

public @interface ConditionalZrumpVOnProperty {

//获取对应property名称的值,与name不可同时使用

String[] value() default {};

//配置属性名称的前缀

String prefix() default "";

//配置属性完整名称或部分名称

/http:///可与prefix组合使用,组成完整的配置属性名称,与value不可同时使用

String[] name() default {};

//可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置

String havingValue() default "";

//缺少该配置属性时是否可以加载。如果为true,没有该配置属性时也会正常加载;反之则不会生效

boolean matchIfMissing() default false;

}

value以及 prefix + name 决定属性值(Property Value),以下为匹配规则

解析:假如havingValue为空,

属性值为boolean类型,则属性值为true 加载该bean,属性值为false 不加载该bean。如果属性值不为boolean类型,则有该属性 则加载bean,没有该属性则不加载。

示例

属性值不是boolean类型的情况

@Bean(name = "emailNotification")

@ConditionalOnProperty(prefix = "notification", name = "service")

public NotificationSender notificationSender() {

return new EmailNotification();

}

如果配置该属性则加载:

notification.service=email

属性值为boolean类型

@Bean(name = "emailNotification")

@ConditionalOnProperty(prefix = "notification", name = "enable")

public NotificationSender notificationSender() {

return new EmailNotification();

}

如果配置为true则加载

notification.enable=true

如果缺失或为false则不加载


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:swagger注解@ApiModelProperty失效情况的解决
下一篇:springboot为异步任务规划自定义线程池的实现
相关文章

 发表评论

暂时没有评论,来抢沙发吧~