有条件的春豆创作

有条件的春豆创作

本文介绍了有条件的春豆创作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Spring注释配置有疑问。我有一个bean:

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,我根本不想建立Web套接字连接。

which signs whether a bean ObservationWebSocketClient should be created. If property value is false I don't want to establich web socket connection at all.

是否有任何技术可能实现这一点?

Is there any technical possibility to realize this?

推荐答案

虽然我没有使用过这个功能,但是看起来你可以用Spring 4的。

Though I've not used this functionality, it appears that you can do this with spring 4's @Conditional annotation.

首先,创建一个 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("createWebSocket"));
    }
}

然后注释你的bean:

Then annotate your bean:

@Bean
@Conditional(MyCondition.class)
public ObservationWebSocketClient observationWebSocketClient(){
    log.info("creating web socket connection...");
    return new ObservationWebSocketClient();
}

编辑 春天-boot 注释 @ConditionalOnProperty 已经实现了这一点;用于评估它的条件的源代码。如果您发现自己经常需要这种功能,那么使用类似的实现是可取的,而不是进行大量的自定义条件实现。

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.

这篇关于有条件的春豆创作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!