Multiple negated profiles

In Spring 5.1.4 (Spring Boot 2.1.2) and above it is as easy as:

@Component
@Profile("!a & !b")
public class MyComponent {}

Ref: How to conditionally declare Bean when multiple profiles are not active?


Spring 4 has brought some cool features for conditional bean creation. In your case, indeed plain @Profile annotation is not enough because it uses OR operator.

One of the solutions you can do is to create your custom annotation and custom condition 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 quick and dirty modification of ProfileCondition.

Now you can annotate your beans in the way:

@Component
@NoProfilesEnabled({"foo", "bar"})
class ProjectRepositoryImpl implements ProjectRepository { ... }

Tags:

Java

Spring