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;
        }
    }
  • 相关阅读:
    sys.stdout.flush-倒计时
    wget 网站扒取
    万能英数脚本
    sample function
    get_time
    读取指定行
    request设置cookies
    resize2fs
    闭包与认识装饰器
    函数的名称空间与作用域
  • 原文地址:https://www.cnblogs.com/kitor/p/14715121.html
Copyright © 2011-2022 走看看