首页 > 代码库 > 002Conditional条件化创建bean

002Conditional条件化创建bean

01、条件化配置bean

@Bean
@Conditional(MagicExistsCondition.class)---->条件化创建bean
public MagicBean magicBean(){
    return new MagicBean();
}

02、条件接口

public interface Condition{
    boolean matches(ConditionContext ctxt, AnnotatedTypeMetadata metadata);
}

03、条件类实现

public class MagicExistsCondition implement Condition {
    public boolean matches( ConditionContext context, AnnotatedTypeMetadata metadata){
        Environment env = context.getEnvironment();
        return env.containsProperty("magic");    ---->检查magic属性
    }
}

04、ConditionContext接口

public interface ConditionContext{
    BeanDefinitionRegistry getRegistry();    ---->检查bean定义
    ConfigurableListableBeanFactory getBeanFactory();    ---->检查bean是否存在,并探查bean的属性
    Environment getEnvironment();    ---->检查环境变量是否存在,及其值是什么
    ResourceLoader getResourceLoader();    ---->探查加载的资源
    ClassLoader getClassLoader();    ---->加载并检查类是否存在
}

05、AnnotatedTypeMetadata接口

public interface AnnotatedTypeMetadata{
    boolean isAnnotated(String annotationType);    ---->判断带@bean的注解,是否还带其它注解
    Map<String, Object> getAnnotationAttributes(String annotationType);    ---->检查其它注解的属性
    Map<String, Object> getAnnotationAttributes(String annotationType, boolean classValuesAsString);
    MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType);
    MultiValueMap<String, Object> getAllAnnotationAttributes(String annotationType, boolean classValuesAsString);
}

06、举例:Profile注解的实现

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile{
    String [] value();
}

class ProfileCondition implements Condition {
    public boolean matches(ConditionContext context, AnnotatedTypeMethodMetadata metadata){
        if(context.getEnvironment() != null){
            MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(Profile.calss.getName());
            if(attrs != null){
                for(Object value : attrs.get("value")){
                    if(context.getEnvironment().acceptsProfiles((String[]) value)){
                        return true;
                    }
                }
                return false;---->没有激活,则不创建bean
            }
        }
        return true;
    }
}

 

002Conditional条件化创建bean