• 【Spring注解】@Condition条件注册


    @Condition条件注册

    @Condition来指定一定条件下注册组件对像
    
    All Conditions that must match in order for the component to be registered.
    
    所有的条件必须实现Condition接口,重写matches方法,来决定组件是否注册

    配置类

    @Configuration
    public class ConditionConfig {
        @Conditional(WindowsCondition.class)
        @Bean("bill")
        public Person bill(){
            return new Person("bill",10);
        }
    
        @Conditional(LinuxCondition.class)
        @Bean("Linus")
        public Person person(){
            return new Person("Linus",10);
        }
    }

    WindowsCondition 判断windows环境

    public class WindowsCondition implements Condition {
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            //获取当前运行环境信息
            Environment environment = context.getEnvironment();
            //获取当前环境名称
            String osName = environment.getProperty("os.name");
            return osName.contains("Windows");
        }
    }

    LinuxCondition 判断Linux环境

    public class LinuxCondition implements Condition {
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            //获取当前运行环境信息
            Environment environment = context.getEnvironment();
            //获取当前环境名称
            String osName = environment.getProperty("os.name");
            return osName.contains("Linux");
        }
    }

    测试(系统为Window 7)

    @Test
    public void person() {
        Map<String, Person> beansOfType = annotationConfigApplicationContext.getBeansOfType(Person.class);
        System.out.println("beansOfType = " + beansOfType);
    }

    设置vm的变量来模拟Linux环境,Run Configurations->VM options
    
    添加 Dos.name=Linux

    运行结果

    ————————————————

    更多参考:https://www.cnblogs.com/mayang2465/p/12019396.html
    原文链接:https://blog.csdn.net/qq_27470131/article/details/79538046

  • 相关阅读:
    Windows phone 墓碑机制的一些源码
    关于Image一些比较抽象的东西(Build Type与 同步以及异步加载的差异)
    自定义控件之Button控件的自定义
    Java集合最全解析,学集合,看这篇就够用了!!!
    看完让你彻底搞懂Websocket原理
    别人的前途我不敢决定
    花一年的时间让自己过得像个人样
    开篇
    你看得懂吗?
    反思
  • 原文地址:https://www.cnblogs.com/koal/p/12360318.html
Copyright © 2020-2023  润新知