简体   繁体   中英

Conditional spring bean creation

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();
}

and I have a property file:

@Autowired
Environment env;

In the property file I want to have a special boolean property

createWebsocket=true/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?

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

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"));
    }
}

Then annotate your bean:

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

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.

Annotate your bean method with @ConditionalOnProperty("createWebSocket") .

Note that Spring Boot offers a number of useful conditions prepackaged.

For Spring Boot 2+ you can simply use:

@Profile("prod")
or
@Profile({"prod","stg"})

That will allow you to filter the desired profile/profiles, for production or staging and for the underlying Bean using that annotation it only will be loaded by Springboot when you set the variable spring.profiles.active is equals to "prod" and ("prod" or "stg"). That variable can be set on OS environment variables or using command line, such as -Dspring.profiles.active=prod.

对我来说,这个问题可以通过使用 Spring 3.1 @Profiles来解决,因为@Conditional注释让你有机会定义一些条件 bean 注册的策略(用户定义的条件检查策略),而@Profiles只能基于Environment的逻辑变量而已。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM