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

@Conditional的作用域:

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

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

3. 方法级别可以放在标识由@Bean的方法上

 

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

 

如果一个@Configuration的类标记了@Conditional,所有标识了@Bean的方法和@Import注解导入的相关类将遵从这些条件。

condition接口定义如下:

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方法,其实就是写规则。

看一个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。

 

转载于:https://my.oschina.net/u/1024107/blog/879456

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值