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[] 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也会有差异。

你可能感兴趣的:(spring 注解--conditional)