@Conditional使用

@Conditional,加载匹配的Bean

进入@Conditional源码
在这里插入图片描述
@Conditional允许指定一个或多个Condition,当所有的Condition均匹配时,说明当前条件成立
在这里插入图片描述
匹配是指Condition#matches(ConditionContext,Annotated TypeMetadata)方法执行后返回true。其中方法参数ConditionContext包含Spring应用上下文相关:BeanDefinitionRegistry、ConfigurableListableBeanFactory、Environment、ResourceLoader和ClassLoader。

自定义@Conditional条件装配

public class OnSystemPropertyCondition implements Condition {
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata metadata) {
        //获取ConditionalOnSystemProperty所有的属性方法值
        MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(ConditionalOnSystemProperty.class.getName());
        //获取ConditionalOnSystemProperty name()方法值
        String ProperyName = (String) attributes.getFirst("name");
        String ProperyValue = (String) attributes.getFirst("value");
        //获取系统属性值
        String property = System.getProperty(ProperyName);
        if (Objects.equals(property,ProperyValue)) {
            System.out.println("----------");
            return true;
        }
        return false;
    }
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(OnSystemPropertyCondition.class)
public @interface ConditionalOnSystemProperty {
    String name();
    String value();
}

@Configuration
public class ConditionalMessageConfigration {

    @ConditionalOnSystemProperty(name="language",value="Chinese")
    @Bean("message")
    public String chineseMessage() {
        return "你好,世界";
    }

    @ConditionalOnSystemProperty(name="language",value="English")
    @Bean("message")
    public String englishMessage() {
        return "hello,world";
    }
}

public class ConditionalOnSystemPropertyBootstrap {
    public static void main(String[] args) {
        System.setProperty("language","Chinese");
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(ConditionalMessageConfigration.class);
        context.refresh();
        String message = context.getBean("message", String.class);
        System.out.println(message);
    }
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值