spring boot 条件化决定是否装配bean

spring boot 条件化决定是否装配bean

1.根据 spring.profiles.active 属性值决定

@Configuration
@Profile("dev")
public class TestConfig {

	@Bean
	//@Profile("dev")
	public MyBean user(){

		return new MyBean();
	}
}

注解 @Profile("*") 当spring.profiles.active 值为 * 时装配

2. 根据Condition装配

@Configuration
public class TestConfig2 {

	@Bean
	@Conditional(MyCondition.class)
	public MyBean user(){

		return new MyBean();
	}
}

class MyCondition implements Condition{


	@Override
	public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

		//获取环境参数
//		String value = context.getEnvironment().getProperty("spring.application.name");
		return true;
	}
}

当 matches 方法返回 true 时装配。

通过ConditionContext,我们可以做到如下几点: 借助getRegistry()返回的BeanDefinitionRegistry检查bean定义; 借助getBeanFactory()返回的ConfigurableListableBeanFactory检查bean是 否存在,甚至探查bean的属性; 借助getEnvironment()返回的Environment检查环境变量是否存在以及它的值是 什么; 读取并探查getResourceLoader()返回的ResourceLoader所加载的资源; 借助getClassLoader()返回的ClassLoader加载并检查类是否存在。

通过AnnotatedTypeMetadata 可以获取bean方法上的注解信息

发布了43 篇原创文章 · 获赞 6 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43866295/article/details/88573935