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}")
Yes, @Profile annotation can be used together with @Component on top of the class representing spring bean.
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)
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.
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".
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