Gaurav
Gaurav

Reputation: 309

Spring conditional @Bean

I need to initialize a bean based on a boolean configuration. If config is true, then initialize the bean else don't load the bean at all (most examples I have seen focus on selecting one implementation out of two). Here's how I am doing it:

@Configuration
public class classA {

    ...
    @Bean
    public XXX createBean(){
        if(config){
            //create bean
        }else{
            return null;
        }
    }
}

I don't feel this is a clean way to achieve this. Need to know if there is a better way to do this.

Spring version: 3.2.1.RELEASE

Upvotes: 4

Views: 1125

Answers (1)

Hasan Can Saral
Hasan Can Saral

Reputation: 3288

You're looking for @ConditionalOnProperty:

@Bean
@ConditionalOnProperty(value = "your.property", havingValue = true)
public YourBean yourBean(){
     return new YourBean();
}

Upvotes: 1

Related Questions