Lachezar Balev
Lachezar Balev

Reputation: 12021

Spring boot: Exclude auto configuration based on environment variable

In spring boot we may exclude specific auto-configuration classes such that they will never be applied. Example with annotation based configuration:

@SpringBootApplication(exclude = OneConfiguration.class)

What I want is to provide an environment variable with a value that will determine some auto configurations that will be excluded. Any ideas how to achieve that?

Upvotes: 13

Views: 17394

Answers (3)

Siim Sindonen
Siim Sindonen

Reputation: 181

You can exclude this configuration class by default:

@SpringBootApplication(exclude = OneConfiguration.class)

then extend it and make it conditonal:

@Configuration
@ConditionalOnProperty(name = "one.configuration.condtion", havingValue = "some-value")
public class OneConfigurationConditional extends OneConfiguration { }

Upvotes: 18

Lachezar Balev
Lachezar Balev

Reputation: 12021

I managed to do what I wanted with profiles :-( So I have few files now - e.g. application-artemis.yaml and application-activemq.yaml. In each I've defined corresponding spring.autoconfigure.exclude property. I'm not proud with this solution though it works fine so far and looks more or less neat compared to other things that I did :-) .

What I've tried besides that:

  1. Managing the value with an environment variable, e.g.:
spring:
  autoconfigure:
    exclude: ${ABC:com.example.Myautoconfiguration}

This does not work and I've even reported it as an issue. But it seems that I can't rely on expression for this property. Strange enough it works for other properties...

  1. I've played around with the suggestion of @Randal Flagg but somehow I couldn't get it up and running - I'm using @SpringBootApplication, the documentation says that I can use EnableAutoConfiguration only once, etc.

  2. I've tried with my own TypeFilter but this is also not an option - autoconfigurations have special treatment during component scan and the design does not seem very extensible there. At least I could not find a nice way to plug in.

Upvotes: 3

Krzysztof Atłasik
Krzysztof Atłasik

Reputation: 22595

Create class extending Condition checking value of enviroment variable:

public class AutoConfigurationCondition extends Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        return System.getenv("EXCLUDE").equals("yes");
     }
}

Then you can use it in Configuration class:

@Configuration
@Conditional(AutoConfigurationCondition.class)
@EnableAutoConfiguration(exclude = {OneConfiguration.class})
class AutoConfigurationExcludingConf {}

Upvotes: 2

Related Questions