Spring @ConditionalOnProperty annotation not working as expected

Viewed 15199

I have a property defined inside a property file: property=true

Then I have SomeClass.java class , which should create a Property Configuration bean only if the property property is set to true.

This is my SomeClass class:

public class SomeClass {

  //this is the proerty which I set to true or false
  @Value("${property}")
  private String property;

  //this is the bean which needs to be created conditionally based on the property but at the moment it does not get created
  @Bean
  @ConditionalOnProperty(name="${property}", havingValue="true")
  public PropertyConfiguration propertyConfig() {
    // doesnt print anything because the bean does not get created
    System.out.print(property);
  }
}

If I add the matchIfMissing = true inside the @ConditionalOnProperty, just to experiment and to see what is the value of property, then the bean does get created and I see that the value of property is true.

If I remove the matchIfMissing = true, leave the condition as @ConditionalOnProperty(name="${property}", havingValue="true") and change the property property=true from true to false the bean is never created (neither for true nor for false).

What should I do s.t. the bean gets created conditionally, based on the property?

1 Answers

Please add @Configuration above your class.

The component scan does not include your class, to do so it is required to add a @Component or any other inherited annotation on top of your class. Then your @Bean should be created from spring.

Hope this helps.

Related