1. 程式人生 > >Spring 學習四 Bean 按條件注入到 IOC 容器中

Spring 學習四 Bean 按條件注入到 IOC 容器中

  • 繼承Condition 介面,在 bean 添加註解 @Conditional

Condition 介面原始碼

@FunctionalInterface
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 the annotated component's registration
    */
   boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);

}

@Conditional 原始碼

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {

	/**
	 * All {@link Condition}s that must {@linkplain Condition#matches match}
	 * in order for the component to be registered.
	 */
	Class<? extends Condition>[] value();

}

linuxwindows
configuration

說明:WindowsCondition 和 LinuxCondition 都繼承 Condition 介面,在 MainConfig 配置類中按條件注入 bean,當執行環境不同時注入不同的 bean 元件