@Conditional-按照條件註冊bean

1.條件註解

​ 能夠根據不一樣的條件來作出不一樣的事情。在Spring中條件註解能夠說是設計模式中狀態模式的一種體現方式,同時也是面向對象編程中多態的應用部分。 在Spring框架中,當咱們使用條件註解時,咱們會爲每種獨立的條件建立一個類,根據這個類對應的條件的成立狀況咱們來選擇不一樣的任務來執行。固然咱們在聲明任務時,通常使用接口來聲明。由於咱們會在Spring的配置類中指定具體條件下的具體類。接下來,咱們未來看一下Spring框架中@Conditional註解的具體使用方式。java

2.配置類

@Configuration
public class MainConfig2 {
	/**
	 * @Conditional({Condition}) : 按照必定的條件進行判斷,知足條件給容器中註冊bean
	 * 
	 * 若是系統是windows,給容器中註冊("bill")
	 * 若是是linux系統,給容器中註冊("linus")
	 */
	@Conditional(WindowsCondition.class)
	@Bean("bill")
	public Person person01(){
		return new Person("Bill Gates",62);
	}
	@Conditional(LinuxCondition.class)
	@Bean("linus")
	public Person person02(){
		return new Person("linus", 48);
	}
}

3.註解條件類

須要建立@Conditional註解所需的條件類。每一個條件類對應着一種獨立的狀況,在Spring中的條件類須要實現Condition接口.linux

liunx
//判斷是否linux系統
public class LinuxCondition implements Condition {
    /**
     * ConditionContext:判斷條件能使用的上下文(環境)
     * AnnotatedTypeMetadata:註釋信息
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //一、能獲取到ioc使用的beanfactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        //二、獲取類加載器
        ClassLoader classLoader = context.getClassLoader();
        //三、獲取當前環境信息
        Environment environment = context.getEnvironment();
        //四、獲取到bean定義的註冊類
        BeanDefinitionRegistry registry = context.getRegistry();

        String property = environment.getProperty("os.name");

        //能夠判斷容器中的bean註冊狀況,也能夠給容器中註冊bean
        boolean definition = registry.containsBeanDefinition("person");
        if(property.contains("linux")){
            return true;
        }
        return false;
    }
}
windows
//判斷是否windows系統
public class WindowsCondition implements Condition {
	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		Environment environment = context.getEnvironment();
		String property = environment.getProperty("os.name");
		if(property.contains("Windows")){
			return true;
		}
		return false;
	}
}
相關文章
相關標籤/搜索