Spring4.0系列4-Meta Annotation(元注解)
Spring4.0系列6-Generic Qualifier(泛型限定)
Spring4.0系列7-Ordering Autowired Collections
更多正在编写中。。。
这篇文章介绍Spring 4的@Conditional注解。在Spring的早期版本你可以通过以下方法来处理条件问题:
- 3.1之前的版本,使用Spring Expression Language(SPEL)。
- 3.1版本有个新特性叫profile,用来解决条件问题。
1、Spring Expression Language(SPEL)
SPEL有一个三元运算符(if-then-else)可以在配置文件中当作条件语句,如下:
<bean id="flag"> <constructor-arg value="#{systemProperties['system.propery.flag'] ?: false }" /> </bean> <bean id="testBean"> <property name="prop" value="#{ flag ? 'yes' : 'no' }"/> </bean>
testBean的prop动态依赖于flag的值。
2、使用Profile
<!-- 如果没有设置profile,default.xml将被加载 --> <!-- 必须放置在配置文件的最底下,后面再也没有bean的定义 --> <beans profile="default"> <import resource="classpath:default.xml" /> </beans> <!-- some other profile --> <beans profile="otherProfile"> <import resource="classpath:other-profile.xml" /> </beans>
3、使用@Conditional
官方文档定义:“Indicates that a component is only eligible for registration when all specified conditions match”,意思是只有满足一些列条件之后创建一个bean。
@Conditional定义
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE, ElementType.METHOD) public @interface Conditional{ Class <!--?extends Condition-->[] value(); }@Conditional注解主要用在以下位置: 类级别可以放在注标识有@Component(包含@Configuration)的类上