Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AND operator in @Profile annotation

I have this configuration class in my Spring Boot appl. v1.5.3.RELEASE

@Configuration
@Profile("dev && cub")
@PropertySource("file:///${user.home}/.cub/application-dev.properties")
public class CubDevelopmentConfig {
..
}

and this property defined in my application.properties

spring.profiles.active=dev, cub

but the config class is not loaded

I also tried @Profile("{dev && cub}")

like image 493
Nunyet de Can Calçada Avatar asked May 13 '17 09:05

Nunyet de Can Calçada


People also ask

Can you use @component together with profile?

Yes, @Profile annotation can be used together with @Component on top of the class representing spring bean.

Which of the following features are enabled using @SpringBootApplication annotation?

A single @SpringBootApplication annotation can be used to enable those three features, that is: @EnableAutoConfiguration : enable Spring Boot's auto-configuration mechanism. @ComponentScan : enable @Component scan on the package where the application is located (see the best practices)

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.


1 Answers

Use the array form of the value() method of the annotation to specify multiple values.
That is : @Profile({"dev", "cub"})

Nevertheless, this configuration don't mean that both "dev" and "cub" profiles are required.
The presence of at least one of them validates the condition.

To enable the configuration only if both profiles are present, Spring Boot didn't provide a solution out of the box so far.
From Spring Core 5.1 (Spring Boot 2.1 or more) you can at last use some expression in @Profile. Beware that are not EL but limited expressions.

A profile string may contain a simple profile name (for example "p1") or a profile expression. A profile expression allows for more complicated profile logic to be expressed, for example "p1 & p2". See Profiles.of(String...) for more details about supported formats.

According to the javadoc, we could specify the presence of multiple profiles as condition :

@Profile("dev & cub")

The presence of one or another profile could be expressed more explicitly now :

@Profile("dev | cub")

And we could also rely on negation, for example :

@Profile("dev & !cub")

Note that & and | cannot be mixed in a same expression without using parenthesis. So it should be used as :

@Profile("(dev & integ) | cub")

You can retrieve all rules concerning Profile expressions here.

As a general note, beware about union of profiles as activation rule because it may be caused by a bad design where we couple too much the "environments".

like image 170
davidxxx Avatar answered Nov 12 '22 02:11

davidxxx