ConditionalOnProperty配置swagger不生效如何解决

发布时间:2022-06-14 14:00:31 作者:iii
来源:亿速云 阅读:683

这篇文章主要介绍“ConditionalOnProperty配置swagger不生效如何解决”,在日常操作中,相信很多人在ConditionalOnProperty配置swagger不生效如何解决问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”ConditionalOnProperty配置swagger不生效如何解决”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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 ConditionalOnProperty {
//获取对应property名称的值,与name不可同时使用
    String[] value() default {};
 
//配置属性名称的前缀
    String prefix() default "";
 
//配置属性完整名称或部分名称
//可与prefix组合使用,组成完整的配置属性名称,与value不可同时使用
    String[] name() default {};
 
//可与name组合使用,比较获取到的属性值与havingValue给定的值是否相同,相同才加载配置
    String havingValue() default "";
 
//缺少该配置属性时是否可以加载。如果为true,没有该配置属性时也会正常加载;反之则不会生效
    boolean matchIfMissing() default false;
}

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

ConditionalOnProperty配置swagger不生效如何解决

解析:假如havingValue为空,

示例

属性值不是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则不加载

到此,关于“ConditionalOnProperty配置swagger不生效如何解决”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. .gitignore不生效
  2. 如何解决php修改参数不生效

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

swagger

上一篇:C语言常见关键字怎么使用

下一篇:如何安装harbor作为docker镜像仓库

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》