• @Conditional的用法


    @Conditional进行条件判断: 符合条件则加载该bean,不符合则不加载该bean 示例

    1、用于测试的bean实体
    package com.bean;

    /**
    * @auto dh
    * @create 2020-04-25-15:10
    */
    public class Animal {
    }

    package com.bean;

    /**
    * @auto dh
    * @create 2020-04-25-11:00
    */
    public class Person {
    }
    2、实现condition的类
    package com.condition;


    import org.springframework.context.annotation.Condition;
    import org.springframework.context.annotation.ConditionContext;
    import org.springframework.core.type.AnnotatedTypeMetadata;

    /**
    * @auto dh
    * @create 2020-04-25-15:11
    */
    public class Condition001 implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata annotatedTypeMetadata) {
    // context 代表Ioc容器 context.getBeanFactory 从Ioc容器里获取容器工厂
    //    调用该容器工厂,判断是否包含该bean名为animal
    if(context.getBeanFactory().containsBean("animal")){
    return true;
    }
    return false;
    }
    }
    3、配置类
    package com.configuration;

    import com.bean.Animal;
    import com.bean.Person;
    import com.condition.Condition001;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Conditional;
    import org.springframework.context.annotation.Configuration;

    /**
    * @auto dh
    * @create 2020-04-25-15:15
    */
    @Configuration
    public class ConditionTest001 {
    // @Bean
    public Animal animal() {
    return new Animal();
    }

    @Bean
    // 如果Condition001.class返回true,则加载该bean,
    // 否则不加载该bean
    @Conditional(Condition001.class)
    public Person person() {
    return new Person();
    }

    }
    4、测试类
    package com.test;

    import org.springframework.context.annotation.AnnotationConfigApplicationContext;

    /**
    * @auto dh
    * @create 2020-04-25-15:16
    */
    public class ConditionTest001 {
    public static void main(String[] args) {
    AnnotationConfigApplicationContext ctx=new AnnotationConfigApplicationContext(com.configuration.ConditionTest001.class);
    String[] beans=ctx.getBeanDefinitionNames();
    for(String str:beans){
    System.out.println("bean信息:"+str);
    }
    }
    }
     
  • 相关阅读:
    D3制作力导向图
    page分页问题,根据页码获取对应页面的数据,接口调用
    python列表生成式、键盘输入及类型转换、字符串翻转、字母大小写、数组广播、循环语句等基础问题
    python中将已有链接的视频进行下载
    机器学习1
    python 排序算法
    LintCode 练习题
    python 装饰器的使用
    hive 学习笔记
    hive 操作
  • 原文地址:https://www.cnblogs.com/kukai/p/12773290.html
Copyright © 2020-2023  润新知