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;
        }
    }
  • 相关阅读:
    GroupCoordinator机制
    Consumer 机制
    Producer机制
    Kafka总体介绍
    为什么使用kafka
    消息队列中点对点与发布订阅区别
    为什么使用消息系统
    人生的诗·290~294节
    唐诗宋词学习·141~145节
    人生的诗·295~299节
  • 原文地址:https://www.cnblogs.com/kitor/p/14715121.html
Copyright © 2011-2022 走看看