简体   繁体   中英

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.

在此处输入图片说明

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM