markthegrea
markthegrea

Reputation: 3841

How can I force SpringBoot to use One and only One of multiple config classes?

I have a project that has two different runtimes in it (one a lambda and one a fargate). I have two different configs but only want one to run.

enter image description here

How do I exclude and include config classes? This didn't seem to work:

@SpringBootApplication(exclude = DynamoConfig.class)

And since they are in the same "path", I can't exclude just the package

com.cat.lakitu.runner

because the "persist" package will be excluded as well.

Upvotes: 1

Views: 1081

Answers (2)

Briano Bruno
Briano Bruno

Reputation: 66

I would use the @ConditonalOnProperty annotation here on two configs, and add the properties in the main of one of the runtimes , take for example lambda (since you said each run uses a different one)

public static void main(String[] args) {
    SpringApplication application = new SpringApplication(DemoApplication.class);
    Properties properties = new Properties();
    properties.put("lambda.application", "true");
    application.setDefaultProperties(properties);
    application.run(args);
}

then on the config needed when run time is lambda you can annotate the bean as such

    @ConditionalOnProperty(
        value="lambda.application",
        havingValue = "true")
public class DyanmoConfig {

Then the other bean could have the following conditional properties

        @ConditionalOnProperty(
        value="lambda.application",
        havingValue = "false",
        matchIfMissing= true)
public class PersistConfig {

This way you only need to set the properties programatically in one of the two main's

Upvotes: 2

Pieterjan Deconinck
Pieterjan Deconinck

Reputation: 552

There are different ways of solving this. Which one you choose depends on your specific use case and needs.

Using profiles: https://www.baeldung.com/spring-profiles

Example:

@Component
@Profile("runtime1")
public class DynamoConfig

Using conditional beans (multiple possibilities): https://reflectoring.io/spring-boot-conditionals/

@Component
@ConditionalOnProperty(
    value="module.enabled", 
    havingValue = "true", 
    matchIfMissing = true)
public class DynamoConfig

Upvotes: 1

Related Questions