Spring loading configuration skip registration on multiple @Profile

I have a Spring boot application with various profile settings: dev , prod , qc , console , etc.

The two configuration classes are configured as follows. MyConfigurationA must be registered for all profiles except console . MyConfigurationB must be registered, except for console and dev .

When I run the application with the console profile, MyConfigurationA does not register - this is normal. But MyConfigurationB registered - which I don't want. I set the @Profile annotation as follows so as not to register MyConfigurationB for the console and dev profile.

But MyConfigurationB registered when the application starts with the console profile.

 @Profile({ "!" + Constants.PROFILE_CONSOLE , "!" + Constants.PROFILE_DEVELOPMENT }) 

The documentation ( http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/Profile.html ) provides an example of including one profile and excluding another. In my example, I exclude as @Profile({"!p1", "!p2"}):

@Profile ({"p1", "! P2"}), registration will occur if Profile 'p1' is active OR if profile 'p2' is not active.

My question is:. How can we skip the registration of configurations of both profiles? @Profile({"!p1", "!p2"}) performs an OR operation. We need operation I.


Code:

 @Configuration @Profile({ "!" + Constants.PROFILE_CONSOLE }) public class MyConfigurationA { static{ System.out.println("MyConfigurationA registering..."); } } @Configuration @Profile({ "!" + Constants.PROFILE_CONSOLE , "!" + Constants.PROFILE_DEVELOPMENT }) // doesn't exclude both, its OR condition public class MyConfigurationB { static{ System.out.println("MyConfigurationB registering..."); } } public final class Constants { public static final String PROFILE_DEVELOPMENT = "dev"; public static final String PROFILE_CONSOLE = "console"; ... } 
+5
source share
1 answer

@Profile({"!console", "!dev"}) means (NOT the console) OR (NOT the dev), which is true if you run the application using the "profile" console.
To solve this problem, you can create a custom Condition :

 public class NotConsoleAndDevCondition implements Condition { @Override public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) { Environment environment = context.getEnvironment(); return !environment.acceptsProfiles("console", "dev"); } } 

And apply the condition using the @Conditional annotation to the Configuration:

 @Conditional(NotConsoleAndDevCondition.class) public class MyConfigurationB { 
+8
source

Source: https://habr.com/ru/post/1242474/


All Articles