Disable Spring Configuration if one of several profiles is present

As expected, this configuration will not load if it moduleTestis an active profile:

@Profile({"!moduleTest"})
@Configuration
public class UserConfig {
}

However, this configuration will load:

@Profile({"!moduleTest", "!featureTest"})
@Configuration
public class UserConfig {
}

Is there a way to have a configuration that will not load if active moduleTestor featureTest?

+4
source share
1 answer

Try using the condition:

@Configuration
@Conditional(LoadIfNotModuleNorTestProfileCondition.class)
public class UserConfig {
}

LoadIfNotModuleNorTestProfileCondition class:

public class LoadIfNotModuleNorTestProfileCondition implements ConfigurationCondition{

    @Override
    public ConfigurationPhase getConfigurationPhase() {
        return ConfigurationPhase.PARSE_CONFIGURATION;
    }

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String[] activeProfiles = context.getEnvironment().getActiveProfiles();
        for (String profile : activeProfiles) {
            if(profile.equalsIgnoreCase("moduleTest") || profile.equalsIgnoreCase("featureTest")){
                return false;
            }
        }
        return true;
    }

}
+7
source

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


All Articles