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

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?

Leave a Comment