Multiple negative profiles
My problem is I have an application that uses Spring profiles. Creating an application on the server means the profile is set to " wo-data-init
". There is a " test
" profile for another assembly . When any of these are activated, they shouldn't trigger the Bean method, so while this annotation should work:
@Profile({"!test","!wo-data-init"})
It looks like it works if(!test OR !wo-data-init)
and in my case I need to run it if(!test AND !wo-data-init)
- is it possible?
source to share
Spring 4 brings some cool features for creating conditional beans . In your case, a really simple annotation is @Profile
not enough since it uses an operator OR
.
One solution you can make is to create your own annotation and custom conditions for it. for example
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Documented
@Conditional(NoProfilesEnabledCondition.class)
public @interface NoProfilesEnabled {
String[] value();
}
public class NoProfilesEnabledCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
boolean matches = true;
if (context.getEnvironment() != null) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(NoProfileEnabled.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
String[] requiredProfiles = (String[]) value;
for (String profile : requiredProfiles) {
if (context.getEnvironment().acceptsProfiles(profile)) {
matches = false;
}
}
}
}
}
return matches;
}
}
Above is a quick and dirty modification to ProfileCondition .
You can now comment out your beans like this:
@Component
@NoProfilesEnabled({"foo", "bar"})
class ProjectRepositoryImpl implements ProjectRepository { ... }
source to share
In Spring 5.1 (Spring Boot 2.1) and up, it's as easy as:
@Component
@Profile("!a & !b")
public class MyComponent {}
Reference: How to conditionally declare a Bean when multiple profiles are not active?
source to share