@Conditional_笔记

本文介绍如何使用Spring框架的@Conditional注解,根据不同的操作系统环境(Windows或Linux)选择性地注册bean。通过自定义实现Condition接口,可以动态决定哪些组件应该被加载到应用上下文中。

@Conditional({}):按照一定的条件进行判断,满足条件给容器中注册bean。 如果将其注解在类上,则是满足当前条件下,这个类中配置的所有bean注册才能生效。 自定义判断条件,需要实现org.springframework.context.annotation的Condition接口,并重写matches()方法。

举个例子:如果系统是Windows,给容器中注册("windows")
                  如果系统是Linux,给容器中注册("linus")

创建一个LinuxCondition类并实现Condition接口

public class LinuxCondition implements Condition{

	/* ConditionContext:判断条件能使用的上下文环境
	 * AnnotatedTypeMetadata:注解的注释信息
	 * 
	 */
	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		// 判断是否是Linux系统
		
		//1、获取当前运行环境,这里面封装了jvm信息,环境变量等
		Environment environment = context.getEnvironment();
		//2、获取到bean定义的注册类
		BeanDefinitionRegistry registry = context.getRegistry();
		
		String property = environment.getProperty("os.name");
		if(property.contains("linux")) {
			return true;
		}
		return false;
	}

}

创建一个WindowsCondition类并实现Condition接口

public class WindowsCondition implements Condition{

	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
		// 判断是否是Windows系统
		Environment environment = context.getEnvironment();
		String property = environment.getProperty("os.name");
		if(property.contains("Windows 10")) {
			return true;
		}
		return false;
	}

}

然后在配置类里进行配置,部分代码如下:

        @Conditional({WindowsCondition.class})
	@Bean("windows")
	public Person person01() {
		return new Person("windows",13);
	}
	
	@Conditional({LinuxCondition.class})
	@Bean("linus")
	public Person person02() {
		return new Person("linus",58);
	}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值