我们可以有条件地申报春豆吗? [英] Can we declare spring bean conditionally?
问题描述
有没有办法可以像有条件地声明一个Spring bean:
Is there a way we can declare a Spring bean conditionally like:
<bean class="path.to.the.class.MyClass" if="${1+2=3}" />
这将是有用的,而不必使用配置文件。
我没有考虑具体的用例,但它来找我。
It would be useful instead of having to use profiles. I don't have a specific use-case in mind, but it came to me.
推荐答案
你可以使用来自Spring 4 的 @Conditional 或来自Spring 引导的 @ConditionalOnProperty 。
You can use @Conditional from Spring4 or @ConditionalOnProperty from Spring Boot.
-
1.使用Spring4(仅),
如果您 NOT 使用spring boot ,此可能过度。
if you are NOT using spring boot, this can be overkill.
首先,创建一个Condition类,其中ConditionContext可以访问环境:
First, create a Condition class, in which the ConditionContext has access to the Environment:
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext context,
AnnotatedTypeMetadata metadata) {
Environment env = context.getEnvironment();
return null != env
&& "true".equals(env.getProperty("server.host"));
}
}
然后注释你的bean:
Then annotate your bean:
@Bean
@Conditional(MyCondition.class)
public ObservationWebSocketClient observationWebSocketClient(){
//return bean
}
- 2.使用Spring Boot :
- 2.Using Spring Boot:
@ConditionalOnProperty(name =server.host,havingValue =localhost)
在您的abcd.properties文件中,
And in your abcd.properties file ,
server.host=localhost
这篇关于我们可以有条件地申报春豆吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!