栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

spring中的@Conditional按照一定的条件进行判断,满足条件给容器中注册bean(springboot中大量使用了)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

spring中的@Conditional按照一定的条件进行判断,满足条件给容器中注册bean(springboot中大量使用了)

@Conditional({Condition}) : 按照一定的条件进行判断,满足条件给容器中注册bean(springboot中大量使用了)

==============================用下面的示例来掩饰其功能=======================

如果系统是windows,给容器中注册("bill")
如果是linux系统,给容器中注册("linus")

spring配置类中我们需要书写的是:

 @Conditional(WindowsCondition.class)
    @Bean("bill")
    public Person person01() {
        return new Person("Bill Gates", 62);
    }

    @Conditional(LinuxCondition.class)
    @Bean("linus")
    public Person person02() {
        return new Person("linus", 48);
    }

随后我们自定义两个判断类:

WindowsCondition:判断是否是windows环境
public class WindowsCondition implements Condition {
    public boolean matches(ConditionContext conditionContext, AnnotatedTypemetadata annotatedTypemetadata) {
        Environment environment = conditionContext.getEnvironment();
        String property = environment.getProperty("os.name");
        while (property.contains("Windows")) {
            return true;
        }
        return false;
    }
}
LinuxCondition:判断是否是linux环境
public class LinuxCondition implements Condition {
    public boolean matches(ConditionContext conditionContext, AnnotatedTypemetadata annotatedTypemetadata) {

       // TODO是否linux系统
		//1、能获取到ioc使用的beanfactory
		ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();

		//2、获取类加载器
		ClassLoader classLoader = context.getClassLoader();

		//3、获取当前环境信息
		Environment environment = context.getEnvironment();

		//4、获取到bean定义的注册类
		BeanDefinitionRegistry registry = context.getRegistry();
		
		String property = environment.getProperty("os.name");
		
		//可以判断容器中的bean注册情况,也可以给容器中注册bean
		boolean definition = registry.containsBeanDefinition("person");
    }
}

在测试类中运行结果可知:bill.

如果想在linux中模拟运行按照下列做法即可

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/711548.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号