4

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

4
  • You are looking for Spring's @Conditional annotation: docs.spring.io/spring/docs/current/javadoc-api/org/… Commented Oct 26, 2014 at 2:37
  • I am on spring 3.2 actually Commented Oct 26, 2014 at 2: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+ Commented Oct 26, 2014 at 2:49
  • 1
    duplicate dynamically declare beans at runtime in Spring Commented Oct 26, 2014 at 2:58

1 Answer 1

1

You're looking for @ConditionalOnProperty:

@Bean
@ConditionalOnProperty(value = "your.property", havingValue = true)
public YourBean yourBean(){
     return new YourBean();
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.