Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally declare Bean when multiple profiles are not active?

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.

like image 900
Mike Boddin Avatar asked Feb 16 '16 09:02

Mike Boddin


People also ask

How do you define beans for a specific profile?

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.

What is conditional Bean?

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.

Can I configure a bean class multiple times?

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).


1 Answers

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?

like image 76
f-CJ Avatar answered Sep 19 '22 13:09

f-CJ