Conditional spring bean creation

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.

Leave a Comment