Spring Load bean conditionally on @ConfigurationProperties value

Spring Boot gives us typed configuration objects using the @ConfigurationProperties annotation. One of the benefits is getting the property name in the IDE for free when using the Spring Boot comment handler. Another will be: verification.

Now I would like to make the bean condition a conditional value of the property. In fact, I have two interface implementations, and this property tells me which one should be used. I could implement it as follows:

ImplementationA.java

 @Component @ConditionalOnProperty(name = "foo.bar", havingValue = "a") public class ImplementationA implements SomeInterface { ... } 

ImplementationB.java

 @Component @ConditionalOnProperty(name = "foo.bar", havingValue = "b") public class ImplementationB implements SomeInterface { ... } 

application.yml

 foo: bar: "a" 

However, I would lose the advantage of a typed configuration. Therefore, I would like to declare this property in the @ConfigurationProperties object:

FooProperties.java

 @ConfigurationProperties(prefix = "foo") public class FooProperties { private String bar; public String getBar() { ... } public void setBar(String bar) { ... } } 

This will work anyway, but when I declare the default value for bar in this class, it obviously will not be picked up by @ConditionalOnProperty , as this annotation is directly related to the Environment (as was developed). Therefore, it may be better not to confuse these concepts.

So the question is ...

Will there be a way to have a conditional bean based on the value in the @ConfigurationProperties object? It is preferable to use some @Conditional annotation without creating an @Configuration bean, as that would mean boilerplate code.

+5
source share

Source: https://habr.com/ru/post/1275757/


All Articles