Can we declare spring bean conditionally?

You can use @Conditional from Spring4 or @ConditionalOnProperty from Spring Boot.

  1. Using Spring4 (only)

if you are NOT using Spring Boot, this can be overkill.

First, create a Condition class, in which the ConditionContext has access to the Environment:

public class MyCondition implements Condition {
    public boolean matches(ConditionContext context,
                           AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        return null != env
                && "true".equals(env.getProperty(""));

Then annotate your bean:

public ObservationWebSocketClient observationWebSocketClient() {
    //return bean

2.Using Spring Boot:

@ConditionalOnProperty(name="", havingValue="localhost")

And in your file ,

Leave a Comment