In my Spring-Boot-App I want to conditionally declare a Bean, depending on (un)loaded spring-profiles.
The conditon:
Profile "a" NOT loaded AND Profile "b" NOT loaded
My solution so far (which works):
@Bean @ConditionalOnExpression("#{!environment.getProperty('spring.profiles.active').contains('a') && !environment.getProperty('spring.profiles.active').contains('b')}") public MyBean myBean(){/*...*/}
Is there a more elegant (and shorter) way to explain this condition?
Especially I want to get rid of the usage of Spring Expression Language here.
Use @Profile on a Bean Let's start simple and look at how we can make a bean belong to a particular profile. We use the @Profile annotation — we are mapping the bean to that particular profile; the annotation simply takes the names of one (or multiple) profiles.
Why do we need Conditional Beans? A Spring application context contains an object graph that makes up all the beans that our application needs at runtime. Spring's @Conditional annotation allows us to define conditions under which a certain bean is included into that object graph.
The class is created as a bean in the "WebAppConfig extends WebMvcConfigurerAdapter" class, which is where the constructor is called. I did some testing and found out that the WebMvcConfigurerAdapter is loaded two or more times(By adding a println to its constructor).
Since Spring 5.1.4 (incorporated in Spring Boot 2.1.2) it is possible to use a profile expression inside profile string annotation. So:
In Spring 5.1.4 (Spring Boot 2.1.2) and above it is as easy as:
@Component @Profile("!a & !b") public class MyComponent {}
In Spring 4.x and 5.0.x:
There are many approaches for this Spring versions, each one of them has its pro's and con's. When there aren't many combinations to cover I personally like @Stanislav answer with the @Conditional
annotation.
Other approaches can be found in this similar questions:
Spring Profile - How to include AND condition for adding 2 profiles?
Spring: How to do AND in Profiles?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With