Spring之@Conditional注解

@Conditional 按照条件注入bean,也可以放在配置类上统一设置条件

配置类:

@Configuration //告诉spring这是个配置类
@ComponentScan(value = "com.spring")
public class SpringConfig {

    /**
     * @Conditional 按照条件注入bean
     * 如果系统是windows则注入该bean
     */
    @Conditional(WindowsCondition.class)
    @Bean
    public Person person01(){
        System.out.println("person01..被创建放入ioc容器...");
        return new Person("windows","22");
    }

    /**
     * @Conditional 按照条件注入bean
     * 如果系统是linux则注入该bean
     */
    @Conditional(LinuxCondition.class)
    @Bean
    public Person person02(){
        System.out.println("person02..被创建放入ioc容器...");
        return new Person("linux","20");
    }
}

自定义实现条件:

public class WindowsCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String property = context.getEnvironment().getProperty("os.name");
        //获取本机操作系统名称
        if (property.contains("Windows")){
            return true;
        }
        return false;
    }
}
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        ClassLoader classLoader = context.getClassLoader();
        //获取本机操作系统名称
        String property = context.getEnvironment().getProperty("os.name");
        if (property.contains("Linux")){
            return true;
        }
        return false;
    }
}

main方法测试ing:
本机为windows系统,结果只向容器中注入了person01方法的对象
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值