【Spring注解系列04】@Condition条件注解

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_37107022/article/details/88878703

1.@Condition条件注解

满足指定条件,则会加载对应的实例或者类。该注解可以作用于类和方法上。

@Condition类属性值中,对应的类,必须是实现Condition接口的类

2.实例

配置类:

@Configuration
public class ConditionalConfig {

    /**
     * @Conditional({Condition}) : 按照一定的条件进行判断,满足条件给容器中注册bean
     *
     * 如果系统是windows,给容器中注册("bill")
     * 如果是linux系统,给容器中注册("linus")
     */
    @Conditional(WindowsCondition.class)
    @Bean("bill")
    public Person bill(){
        return new Person("111","Bill Gates");
    }

    @Conditional(LinuxCondition.class)
    @Bean("linus")
    public Person linus(){
        return new Person("222","linus");
    }

}

可以通过设置虚拟机dos名称来改变系统名称。

条件类:必须实现Condition接口

public class LinuxCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        // TODO是否linux系统
        //1、能获取到ioc使用的beanfactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //2、获取类加载器
        ClassLoader classLoader = context.getClassLoader();
        //3、获取当前环境信息
        Environment environment = context.getEnvironment();
        //4、获取到bean定义的注册类
        BeanDefinitionRegistry registry = context.getRegistry();

        System.out.println("environment.getProperty(os.name)---->"+environment.getProperty("os.name"));
        if (environment.getProperty("os.name").contains("Linux")){
            return true;
        }

        return false;
    }
}


public class WindowsCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment environment = context.getEnvironment();
        System.out.println("environment.getProperty(os.name)---->" + environment.getProperty("os.name"));
        if (environment.getProperty("os.name").contains("Windows")) {
            return true;
        }

        return false;
    }
}

测试类:

public class ConditionalTest {

    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(ConditionalConfig.class);
//        Person linus = (Person) applicationContext.getBean("linus");
        Person bill = (Person) applicationContext.getBean("bill");
//        System.out.println("linus----->"+linus);
        System.out.println("bill----->"+bill);
    }
}

测试结果:

environment.getProperty(os.name)---->Windows 7
environment.getProperty(os.name)---->Windows 7
bill----->Person{id='111', name='Bill Gates'}

猜你喜欢

转载自blog.csdn.net/baidu_37107022/article/details/88878703