zoukankan      html  css  js  c++  java
  • @Conditional与Condition接口

    @Conditional来指定一定条件下注册组件对像所有的条件必须实现org.springframework.context.annotation.Condition接口,重写matches方法,通过matches中的返回值(boolean)来决定组件是否注册

    下方案例依赖于Spring的依赖+Lombok

    @Slf4j
    public class Test1 {
    
        @Test
        public void t1() {
            ApplicationContext ac = new AnnotationConfigApplicationContext(MainCfg.class);
            System.out.println("
    
    
    
    
    ");
            log.debug("{}", ac.getBean("person", Person.class));
            log.debug("{}", ac.getBean("person1", Person.class));
        }
    }
    
    @Configuration
    class MainCfg {
    
        @Bean
        @Conditional(CustomCondition1.class)
        public Person person() {
            return new Person();
        }
        @Bean
        @Conditional(CustomCondition2.class)
        public Person person1() {
            return new Person();
        }
    }
    
    @Data
    class Person {
        private String name;
        private int age;
    }
    
    @Slf4j
    class CustomCondition1 implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            log.debug("自定义condition返回true,使用该注解部分应该被加载!");
            return true;
        }
    }
    
    @Slf4j
    class CustomCondition2 implements Condition {
        @Override
        public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
            log.debug("自定义condition返回false,使用该注解的部分不因该被加载!");
            return false;
        }
    }
  • 相关阅读:
    人一生要去的100个地方(世界)
    数据仓库相关书籍
    学理财要看的书籍
    数仓设计 Building the Data Warehouse
    Google Cloud 安装java
    Google Cloud install python3 (in CentOS)
    SyntaxError: Non-ASCII character 'xe5' in file test23.py on line 2, but no encoding declared;
    CentOS 安装7z
    CentOS 安装 MySQL
    复杂迭代代码分析
  • 原文地址:https://www.cnblogs.com/kitor/p/14715121.html
Copyright © 2011-2022 走看看