spring 相关

spring 注解--conditional

2018-12-31  本文已影响0人  aix91

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. 用例

    @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);
    }
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也会有差异。

上一篇 下一篇

猜你喜欢

热点阅读