zoukankan      html  css  js  c++  java
  • 【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

  • 相关阅读:
    Java经典编程题50道之四十一
    Java经典编程题50道之四十
    Java经典编程题50道之三十九
    Java经典编程题50道之三十八
    Java经典编程题50道之三十七
    Java经典编程题50道之三十六
    Java经典编程题50道之三十五
    前端学习之路之CSS (一)
    Numpy 01
    Python3 urllib 与 Python2 urllib的变化
  • 原文地址:https://www.cnblogs.com/koal/p/12360318.html
Copyright © 2011-2022 走看看