@Conditional series of notes examples

1. @Conditional

Description: Condition specified implementation class, then the method returns true matches injection bean, false not injected.

@Configuration
 public  class BeanConfig { 
 
    // only one class, the braces can be omitted
     // if WindowsCondition implemented method returns true, this injection the bean     
    @Conditional ({WindowsCondition. Class }) 
    @Bean (name = "Bill" )
     public PERSON1 the Person () {
         return  new new the Person ( "Bill Gates", 62 is ); 
    } 
 
    // if LinuxCondition implemented method returns true, this injection the bean 
    @Conditional ({LinuxCondition. class }) 
    @Bean ( "Linus" )
     public the Person PERSON2 () {
         return  new new the Person ( "of Linus", 48);
    }
}

Creating LinuxCondition and WindowsCondition class and implement the interface Condition

public class LinuxCondition implements 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. @ConditionalOnBean

Description: The mere presence of an object in the current context, the only instance of a Bean

//RedisOperBean依赖redisTemplate
@Component
@ConditionalOnBean(name="redisTemplate")
public class RedisOperBean {
  private final RedisTemplate redisTemplate;
  public RedisOperBean(RedisTemplate redisTemplate) {
      // ...
  }
}

 

3. @ConditionalOnClass

Note: a class on the classpath, will instantiate a Bean, the requirements specified class must exist

 

4. @ConditionalOnProperty

Description:

Guess you like

Origin www.cnblogs.com/myf008/p/11003879.html