有条件的spring bean创建 [英] Conditional spring bean creation
问题描述
我有一个关于 Spring 注释配置的问题.我有一颗豆子:
I have a question about Spring annotation configurations. I have a bean:
@Bean
public ObservationWebSocketClient observationWebSocketClient(){
log.info("creating web socket connection...");
return new ObservationWebSocketClient();
}
我有一个属性文件:
@Autowired
Environment env;
在属性文件中我想要一个特殊的布尔属性
In the property file I want to have a special boolean property
createWebsocket=true/false
表示是否应创建 bean ObservationWebSocketClient.如果属性值为false,我根本不想建立网络套接字连接.
which signs whether a bean ObservationWebSocketClient should be created. If property value is false I don't want to establish web socket connection at all.
是否有任何技术可能性来实现这一点?
Is there any technical possibility to realize this?
推荐答案
虽然我没有使用过这个功能,但似乎你可以用 spring 4 的 @Conditional
注释.
Though I've not used this functionality, it appears that you can do this with spring 4's @Conditional
annotation.
首先创建一个Condition
类,其中ConditionContext
可以访问Environment
:
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("createWebSocket"));
}
}
然后注释你的bean:
Then annotate your bean:
@Bean
@Conditional(MyCondition.class)
public ObservationWebSocketClient observationWebSocketClient(){
log.info("creating web socket connection...");
return new ObservationWebSocketClient();
}
edit spring-boot
注释 @ConditionalOnProperty
已经通用实现了这一点;用于评估它的 Condition
的源代码 可在 github 上找到,供感兴趣的人使用.如果您发现自己经常需要这种功能,建议使用类似的实现,而不是制作大量自定义 Condition
实现.
edit The spring-boot
annotation @ConditionalOnProperty
has implemented this generically; the source code for the Condition
used to evaluate it is available on github here for those interested. If you find yourself often needing this funcitonality, using a similar implementation would be advisable rather than making lots of custom Condition
implementations.
这篇关于有条件的spring bean创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!