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 组件

猜你喜欢

转载自blog.csdn.net/qq_22925909/article/details/85010864
今日推荐