Conditional spring bean creation

后端 未结 4 1315
悲哀的现实
悲哀的现实 2020-12-03 04:42

I have a question about Spring annotation configurations. I have a bean:

@Bean 
public ObservationWebSocketClient observationWebSocketClient(){
    log.info(&         


        
相关标签:
4条回答
  • 2020-12-03 04:54

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

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

    0 讨论(0)
  • 2020-12-03 04:56

    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 O.S. environment variables or using command line, such as -Dspring.profiles.active=prod.

    0 讨论(0)
  • 2020-12-03 04:59

    As for me, this problem can be solved by using Spring 3.1 @Profiles, because @Conditional annotation give you opportunity for define some strategy for conditional bean registration (user-defined strategies for conditional checking), when @Profiles can based logic only on Environment variables only.

    0 讨论(0)
  • 2020-12-03 05:08

    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.

    0 讨论(0)
提交回复
热议问题