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

  • 相关阅读:
    UDP——python网络编程笔记
    2018.7计划
    二叉树
    第7.5章:类——Cookbook笔记
    网络编程 Cookbook
    网络编程 csapp
    第5.5章 迭代器与生成器——CookBook笔记
    第3.5章 数据结构与算法——CookBook笔记
    关于排序
    关于搜索
  • 原文地址:https://www.cnblogs.com/koal/p/12360318.html
Copyright © 2011-2022 走看看