spring中@Conditional用于选择加载制定bean

@Conditional的做用域:java

1. 类级别能够放在注标识有@Component(包含@Configuration)的类上linux

2. 做为一个meta-annotation,组成自定义注解spring

3. 方法级别能够放在标识由@Bean的方法上windows

 

3.1版本的spring 其实提供了profile,在spring4中能够使用@profile注解。ide

 

若是一个@Configuration的类标记了@Conditional,全部标识了@Bean的方法和@Import注解导入的相关类将听从这些条件。操作系统

condition接口定义以下:code

public interface Condition{  
/** Determine if the condition matches. 
* @param context the condition context 
* @param metadata meta-data of the {@link AnnotationMetadata class} or 
* {@link Method method} being checked. 
* @return {@code true} if the condition matches and the component can be registered 
* or {@code false} to veto registration. 
*/  
boolean matches(ConditionContext context, AnnotatedTypeMedata metadata);  
}

若是要使用这个注解,须要实现这个接口,并重写matches方法,其实就是写规则。component

看一个demo:接口

import org.springframework.context.annotation.Condition;  
import org.springframework.context.annotation.ConditionContext;  
import org.springframework.core.type.AnnotatedTypeMetadata;  
   
public class LinuxCondition implements Condition{  
   
  @Override  
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {  
    return context.getEnvironment().getProperty("os.name").contains("Linux");  }  
}
import org.springframework.context.annotation.Condition;   
import org.springframework.context.annotation.ConditionContext;   
import org.springframework.core.type.AnnotatedTypeMetadata;   
   
public class WindowsCondition implements Condition{  
   
  @Override   
  public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {  
    return context.getEnvironment().getProperty("os.name").contains("Windows");  
  }  
}

咱们有两个类LinuxCondition 和WindowsCondition 。两个类都实现了Condtin接口,重载的方法返回一个基于操做系统类型的布尔值。作用域

下面咱们定义两个bean,一个符合条件另一个不符合条件:

import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Conditional;  
import org.springframework.context.annotation.Configuration;  
   
@Configuration  
public class MyConfiguration {  
   
  @Bean(name="emailerService")  
  @Conditional(WindowsCondition.class)  
  public EmailService windowsEmailerService(){  
      return new WindowsEmailService();  
  }  
   
  @Bean(name="emailerService")  
  @Conditional(LinuxCondition.class)  
  public EmailService linuxEmailerService(){  
    return new LinuxEmailService();  
  }  
}

这样写完之后,当项目启动时,会先从系统环境变量读取 os.name的值,来判断到底应该加载哪个bean。

相关文章
相关标签/搜索