spring 注解--conditional

1. conditional 用途

只注入满足定义条件的bean

2. 用法

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();
}

可以看到要使用conditional注解,得implement condition 定义自己的条件注解。

3. 用例

  • 给要注入的bean添加Conditional注解
    @Conditional(WindowsCondition.class)
    @Bean(name = "bill")
    public Person person2() {
        return new Person("Bill", 62);
    }

    @Conditional(LinuxCondition.class)
    @Bean(name = "linus")
    public Person person3() {
        return new Person("Linus", 50);
    }
  • 定义自己的Condition class
public class LinuxCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        if (env.getProperty("os.name") == "linux") return true;
        return false;
    }
}

public class WindowsCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        String property = env.getProperty("os.name");
        if (property == "linux")
            return true;
        return false;
    }
}

如此,根据环境的不同,注入的bean也会有差异。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容