1. 程式人生 > >spring註解第03課 按條件加載Bean @Conditional

spring註解第03課 按條件加載Bean @Conditional

metadata pri 如果 matches .get factor ade type bool

package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import com.atguigu.bean.Person;
import com.atguigu.condition.LinuxCondition;
import com.atguigu.condition.WindowsCondition;
import com.atguigu.test.IOCTest; //類中組件統一設置。滿足當前條件,這個類中配置的所有bean註冊都能生效; @Conditional({WindowsCondition.class}) @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); } }

2.條件1

package com.atguigu.condition;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; import org.springframework.beans.factory.support.BeanDefinitionRegistry; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.env.Environment; import org.springframework.core.type.AnnotatedTypeMetadata; //判斷是否linux系統 public class LinuxCondition implements Condition { /** * ConditionContext:判斷條件能使用的上下文(環境) * AnnotatedTypeMetadata:註釋信息 */ @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(); String property = environment.getProperty("os.name"); //可以判斷容器中的bean註冊情況,也可以給容器中註冊bean boolean definition = registry.containsBeanDefinition("person"); if(property.contains("linux")){ return true; } return false; } }

3.條件2

package com.atguigu.condition;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;

//判斷是否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;
    }

}

spring註解第03課 按條件加載Bean @Conditional