Spring中的@Conditional注解

欢迎浏览我的博客 获取更多精彩文章

https://boyn.top

Spring中的@Conditional注解

在基于Java代码进行配置的Spring Boot项目中,我们经常会用到Conditional注解.当我们想要满足某些条件时才让Bean容器加载特定的Bean或者模块,或者在不同环境中应用不同的模块.这个时候,@Conditional注解对我们就大有作用.

@Conditional在哪

@Bean

如果我们将@Conditional加在@Bean的定义方法上,就表明只有当@Conditional的条件被满足后,这个Bean才会被加载

@Configuration

如果我们将@Conditional加在@Configuration的定义方法上,就表明只有当@Conditional的条件被满足后,这个配置类才会被加载,通常用于不同环境的部署

@Component, @Service, @Repository或者 @Controller:

与放在@Bean上起到的作用是一样的

预定义的@ConditionalOn*

在Spring中,已经有一些预定义好了的@Condition拓展注解,让我们用起来更方便

@ConditionalOnProperty

当配置文件中某些值满足条件时,才会进行加载.这个注解是用于根据配置文件中的值来定义.

我们来看一个实际的例子

	@Bean("fastJsonHttpMessageConverter")
    @ConditionalOnProperty(value = "json.choice",havingValue = "havetime",matchIfMissing = false)
    FastJsonHttpMessageConverter fastJsonHttpMessageConverterHaveTime(){
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy/MM/dd-HH:mm:ss");
        converter.setFastJsonConfig(config);
        return converter;
    }

    @Bean("fastJsonHttpMessageConverter")
    @ConditionalOnProperty(value = "json.choice",havingValue = "notime",matchIfMissing = true)
    FastJsonHttpMessageConverter fastJsonHttpMessageConverterNoTime(){
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setDateFormat("yyyy/MM/dd");
        converter.setFastJsonConfig(config);
        return converter;
    }

在一个配置类中,定义了两个不同的Fastjson的converter,value表示在配置文件中的选项,此处是json.choice havingValue是一个条件,表示当配置项为这个值的时候,才会加载这个Bean.最后的matchIfMissing表示如果配置文件中没有定义这一项的话,就创造这个类,即一个默认的创建方法.当有多个同样的注解时,建议只有一个注解里面的matchIfMissing为true

我们在配置文件中,有如下语句

 json.choice=notime

我们的打印值为

“time”:“2019/08/21”

当改为havetime之后

“time”:“2019/08/21-17:45:06”

如果直接删除配置项,则效果等同于notime的时候,因为我们设置了notime上的注解中的matchIfMissing为true

@ConditionalOnExpression

这个是上面一个注解的多表达式版本,当我们设定需要多个值才能够进行匹配时,就可以采用这个注解.它需要用SpEL.表达式进行表示

比如我们在上面的一个例子中,规定除了有json.choice外,还要设置json.converter=fastjson,那么我们可以写成以下表达:

@Bean
@ConditionalOnExpression("${json.choice:notime} and ${json.converter:fastjson}")

@ConditionalOnBean

对其传入一个Bean的类对象,只有当这个类对象有加载Bean才会匹配

@ConditionalOnMissingBean

与上面相反,只有当这个类对象没有加载Bean才会匹配

@CondigtionalOnResource

传入一个文件,如

@ConditionalOnResource(resources = "classpath:/logback.xml")

只有当这个资源文件有效,才会匹配

@ConditionalOnClass

只有这个类在classpath中,才会加载Bean.这个注解通常用于Spring框架的开发中,而不是一般的Web应用

@ConditionalOnMissingClass

与上面相反

常规的Conditional注解

我们可以通过实现Condition接口,来实现我们的Conditional注解.

假如我们想要检测这个应用是否在Linux上面运行,则可以先定义一个Condition的子类

public class OnWindowsSys implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //windows == 1, unix == 2
        return SystemUtil.getOSType() == 1;
    }
}

然后可以这样使用

@Conditional(OnWindowsSys.class)

实现逻辑功能

or功能,会匹配这个类里面的@Conditional接口

class OnWindowsOrUnixCondition extends AnyNestedCondition {

  OnWindowsOrUnixCondition() {
    super(ConfigurationPhase.REGISTER_BEAN);
  }

  @Conditional(OnWindowsSys.class)
  static class OnWindows {}

  @Conditional(OnUnixSys.class)
  static class OnUnix {}

}

与OR功能相似,分别继承各个类,可以实现不同的逻辑功能

AnyNestedConditionAllNestedConditionsNoneNestedCondition
ORANDNOT

为了避免凌乱,我们可以自己定义@ConditionalOn*接口,例子如下

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(OnLinuxCondition.class)
public @interface ConditionalOnUnix {}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值