天天看點

spring應用手冊-IOC(注解實作)-(15)[email protected]注解

戴着假發的程式員出品 抖音ID:戴着假發的程式員 歡迎關注

@Conditional注解

spring應用手冊(第二部分)

源碼:

package org.springframework.context.annotation;

@java.lang.annotation.Target({java.lang.annotation.ElementType.TYPE, java.lang.annotation.ElementType.METHOD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Documented
public @interface Conditional {
    java.lang.Class<? extends org.springframework.context.annotation.Condition>[] value();
}
           

@Conditional可以注解在由spring管理的類上方和@bean注解的方法上方。

主要作用是配置一些注冊bean對應的條件,如果滿足條件就注冊bean,如果不滿足就不進行bean的注冊。

我看到 @Conditional屬性value是一組Condition的類型數組。

我們再來看看Condition源碼:

package org.springframework.context.annotation;

@java.lang.FunctionalInterface
public interface Condition {
    boolean matches(org.springframework.context.annotation.ConditionContext conditionContext, org.springframework.core.type.AnnotatedTypeMetadata annotatedTypeMetadata);
}
           

該接口中隻有一個metches方法,傳回true說明條件成立,傳回false說明條件不成立。

我們可以自己實作一個。

看案例:

我們自己實作一個Condition。

/**
 * @author 戴着假發的程式員
 *  
 * @description
 */
public class WindosCondition implements Condition {
    /**
     *
     * @param conditionContext 判斷條件的上下文環境,可以擷取環境對象,和工廠對象
     * @param annotatedTypeMetadata  注解所在位置的注釋資訊
     * @return
     */
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //擷取環境對象
        Environment environment = conditionContext.getEnvironment();
        //判斷環境的名字
        if(environment.getProperty("os.name").contains("Windows")){
            return true;
        }
        return false;
    }
}
           

在AuthorDAO上添加配置:

spring應用手冊-IOC(注解實作)-(15)[email protected]注解

測試:

spring應用手冊-IOC(注解實作)-(15)[email protected]注解

修改條件,再測試。