3

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

Gaurav
  • 299
  • 2
  • 10
  • You are looking for Spring's @Conditional annotation: http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Conditional.html – Angad Oct 26 '14 at 02:37
  • I am on spring 3.2 actually – Gaurav Oct 26 '14 at 02:44
  • Unless your conditional check is somewhere tied to the environment profile, you would not have a cleaner way to achieve this. You can check out @Profile configuration otherwise. I would however recommend upgrading to Spring 4+ – Angad Oct 26 '14 at 02:49
  • 1
    duplicate [dynamically declare beans at runtime in Spring](http://stackoverflow.com/q/15328904/1066779) – Abhishek Nayak Oct 26 '14 at 02:58

1 Answers1

1

You're looking for @ConditionalOnProperty:

@Bean
@ConditionalOnProperty(value = "your.property", havingValue = true)
public YourBean yourBean(){
     return new YourBean();
}
Hasan Can Saral
  • 2,950
  • 5
  • 43
  • 78