Spring Boot注解:@Conditional @ConditionalOnMissingBean @ConditionalOnBean注解使用

1、@Conditional
按照条件注入Bean
1、实现Condition接口并按自己的逻辑返回true /false ,返回true最后Bea会注入,否则相反

@Configuration
public class BeanConfig {
 
    //只有一个类时,大括号可以省略
    //如果WindowsCondition的实现方法返回true,则注入这个bean    
    @Conditional({WindowsCondition.class})
    @Bean(name = "bill")
    public Person person1(){
        return new Person("Bill Gates",62);
    }
 
    //如果LinuxCondition的实现方法返回true,则注入这个bean
    @Conditional({LinuxCondition.class})
    @Bean("linus")
    public Person person2(){
        return new Person("Linus",48);
    }
}
//linux类

public class LinuxCondition implements Condition {//实现Condition接口

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
 
        Environment environment = conditionContext.getEnvironment();
 
        String property = environment.getProperty("os.name");
        if (property.contains("Linux")){
            return true;
        }
        return false;
    }
}

2、@ConditionalOnMissingBean
当容器中没有当前类型Bean时则注入

@Configuration
public class BeanConfig {
    @Bean(name = "notebookPC")
    public Computer computer1(){
        return new Computer("笔记本电脑");
    }
    @ConditionalOnMissingBean(Computer.class)
    @Bean("reservePC")
    public Computer computer2(){
        return new Computer("备用电脑");
    }
}

3、 @ConditionalOnBean
当容器中存在某类型的Bean时才注入容器,否则不注入容器

你可能感兴趣的:(Spring,Boot,spring,boot)