Spring Boot Configuration skip registration on multiple @Profile
Starting with Spring 5.1 you can use expressions in @Profile
annotation. Read more in the @Profile documentation. Example:
@Configuration
@Profile({ "!console & !dev" })
public class MyConfigurationB {
static{
System.out.println("MyConfigurationB registering...");
}
}
With newer versions of Spring, the acceptsProfiles
method which accepts strings has been deprecated.
To do the equivalent work as in Cyril's question, you would need to leverage the new method parameter. This newer format also gives you the flexibility to author profile expressions which are more powerful than what was in place prior, thus eliminating the need to negate the entire acceptsProfiles
expression itself.
public class NotConsoleAndDevCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
return environment.acceptsProfiles(Profiles.of("!console & !dev"));
}
}
@Profile({"!console", "!dev"})
means (NOT console) OR (NOT dev) which is true if you run your app with the profile 'console'.
To solve this 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 via the @Conditional annotation to the Configuration:
@Conditional(NotConsoleAndDevCondition.class)
public class MyConfigurationB {