美文网首页spring 相关
spring 注解--conditional

spring 注解--conditional

作者: aix91 | 来源:发表于2018-12-31 11:32 被阅读0次

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

    相关文章

      网友评论

        本文标题:spring 注解--conditional

        本文链接:https://www.haomeiwen.com/subject/cduilqtx.html