1. 程式人生 > >Spring4.0系列[email protected]

Spring4.0系列[email protected]

one window 標識 cto ace ted ada bsp 布爾

這篇文章介紹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)的類上
  • 作為一個meta-annotation,組成自定義註解
  • 方法級別可以放在標識由@Bean的方法上

如果一個@Configuration的類標記了@Conditional,所有標識了@Bean的方法和@Import註解導入的相關類將遵從這些條件。

condition接口定義如下:

public interface Condition {

    /**
     * Determine if the condition matches.
     * @param context the condition context
     * @param metadata metadata of the {@link org.springframework.core.type.AnnotationMetadata class}
     * or {@link org.springframework.core.type.MethodMetadata 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, AnnotatedTypeMetadata metadata);

}

下面看一個例子:

Java代碼 技術分享
  1. import org.springframework.context.annotation.Condition;
  2. import org.springframework.context.annotation.ConditionContext;
  3. import org.springframework.core.type.AnnotatedTypeMetadata;
  4. public class LinuxCondition implements Condition{
  5. @Override
  6. public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
  7. return context.getEnvironment().getProperty("os.name").contains("Linux"); }
  8. }

Java代碼 技術分享
  1. import org.springframework.context.annotation.Condition;
  2. import org.springframework.context.annotation.ConditionContext;
  3. import org.springframework.core.type.AnnotatedTypeMetadata;
  4. public class WindowsCondition implements Condition{
  5. @Override
  6. public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
  7. return context.getEnvironment().getProperty("os.name").contains("Windows");
  8. }
  9. }

我們有兩個類LinuxCondition 和WindowsCondition 。兩個類都實現了Condtin接口,重載的方法返回一個基於操作系統類型的布爾值。

下面我們定義兩個bean,一個符合條件另外一個不符合條件:

Java代碼 技術分享
  1. import org.springframework.context.annotation.Bean;
  2. import org.springframework.context.annotation.Conditional;
  3. import org.springframework.context.annotation.Configuration;
  4. @Configuration
  5. public class MyConfiguration {
  6. @Bean(name="emailerService")
  7. @Conditional(WindowsCondition.class)
  8. public EmailService windowsEmailerService(){
  9. return new WindowsEmailService();
  10. }
  11. @Bean(name="emailerService")
  12. @Conditional(LinuxCondition.class)
  13. public EmailService linuxEmailerService(){
  14. return new LinuxEmailService();
  15. }
  16. }

當符合某一個條件的時候,這裏的@Bean才會被初始化。

Spring4.0系列[email protected]