@Conditional注解分析

@Conditional注解分析

  • @Conditional注解
    • 例子

@Conditional注解

我们需要Bean在满足一定条件下才允许注入Spring容器的情况,可以加注@Conditional注解。加注了此注解的Bean在定义被Spring注册前会被条件判断。自定义注解标注@Conditional也不允许声明为@Inherited。

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
	/**
	 * Bean被注册一定需要所有Condition都满足
	 */
	Class<? extends Condition>[] value();
}

源码分析:
@Conditional注解分析_第1张图片

例子

   //满足条件才初始化
    @Conditional(value = {WinConditionUsage.class,LinuxConditionUsage.class})
    @Bean
    public ConditionEntity windows() {
        return new ConditionEntity("windows");
    }
//自定义Condition类需要实现Condition接口,多个Condition条件时可以实现Order或子接口PriorityOrdered,用于执行顺序排序
public class WinConditionUsage implements Condition, Ordered {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        //IOC容器正在使用的BeanFactory
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        Environment environment = context.getEnvironment();
        String os_name = environment.getProperty("os.name");
        if (os_name.contains("Windows")) {
            return true;
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 2;
    }
}

你可能感兴趣的:(Spring,spring)