• @Conditional 注解,基于条件实例对象


    1.说明:基于条件,判断是否实例化对象,注入容器中,组合@bean注解使用和扫描。

    2.源代码

            @Target({ElementType.TYPE, ElementType.METHOD}) // 注解在类、方法使用
            @Retention(RetentionPolicy.RUNTIME)
            @Documented
            public @interface Conditional {
    
                Class<? extends Condition>[] value(); // 1.注解值必须继承Condition,2.值为单个值或数组
    
            }
        @FunctionalInterface
            public interface Condition {
                boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);//返回false,条件不成立。目标动作不执行,返回true,条件成立执行目标动作。
            }

    3.使用方式:创建 Condition 的实现类 TsetCondition,使用@Condition(value= TsetCondition.class)

    1.使用在类:条件成立实例化对象,注入容器

    基于条件创建被标注的类,可以结合 @Service ,@Component ,@Controller 三个注解使用,条件成立,创建实例。

              @Component
                    @Conditional(value = TestCondition.class)
                    public class Tst  {
                        @Scheduled(fixedRate = 5000)
                        public  void  getStr() {
                            System.err.println("我的scheduled 执行了");
                        }
                    }

    也可以结合 @Configuration ,@Bean 基于配置文件,条件不成立@Configuration标注的类不创建,类下被标注的@Bean方法不执行

                    @Configuration
                    @Conditional(value = TestCondition.class)
                    public class TestConfiguration {
                        
                        @Bean
                        public Tst createTst() {
                            return new Tst();
                        }
                    }

    2.在方法上使用

    结合@Bean注解使用 ,条件成立方法执行,创建对象实例。

                @Configuration
                public class TestConfiguration {
                    
                    @Bean
                    @Conditional(value = TestCondition.class)
                    public Tst createTst() {  // 基于条件实例化Bean
                        return new Tst();
                    }
                    
                    @Bean
                    public Tst2 createTst2() { //没有条件、只要系统启动就会创建Tst2实例
                        return new Tst2();
                    }
                }

    3.多条件件使用(方法和类):会执行每个 Condition的 matches ,如果有一个返回false ,条件不成立目标不执行

                @Configuration
                public class TestConfiguration {
                    
                    @Bean
                    @Conditional(value = {TestCondition.class,TestCondition2.class})
                    public Tst createTst() {  // 基于条件实例化Bean,只有 TestCondition 、TestCondition2 都返回true才实例化对象,就是说,value集合中只要有一个Condition不成立,就不会实例对象
                        return new Tst();
                    }
                }
  • 相关阅读:
    css选择器(常规选择器,伪类选择器,伪元素选择器,根元素选择器)
    css文件引人的三种方式
    《软件测试》阅读笔记
    测试风险管理
    软件缺陷分析
    软件文档
    软件缺陷分析方法
    软件缺陷分析方法:ODC
    [转载]web测试方法总结
    测试报告笔记
  • 原文地址:https://www.cnblogs.com/jonrain0625/p/11231715.html
Copyright © 2020-2023  润新知