0

I want to externalize the @SpringBootApplication(exclude...) option, to have a reusable class or annotation that I could throw in to exclude any database/hibernate initialization.

So, instead of writing:

@SpringBootApplication(
        exclude = {
                DataSourceAutoConfiguration.class,
                DataSourceTransactionManagerAutoConfiguration.class,
                HibernateJpaAutoConfiguration.class})
public class MainApp {
}

I would like to create a annotation that I could apply to my @SpringBootApplication main class:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@EnableAutoConfiguration(exclude = {
        DataSourceAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class})
@Configuration
public @interface ExcludeDataSources {
}

And then enable this feature by annotation:

@SpringBootApplication
@ExcludeDataSources
public class MainApp {
}

Problem: the annotation approach does not work, and spring still tries to load a database. Why?

My final goal is to have multiple startup classes, where only one loads the database.

3
  • @SpringBootApplication contains @EnableAutoConfiguration without excludes, I am not sure which annotation will be chosen by Spring's meta annotation logic, but I would replace @SpringBootApplication with its annotations (except @EnableAutoConfiguration of course) Commented Dec 7, 2021 at 14:14
  • Why not set the configuration property spring.autoconfigure.exclude to the list of auto-configuration classes to exclude? Set this configuration property inside a profile. Commented Dec 7, 2021 at 20:45
  • @ChinHuang because I don't run my application in different profiles (different jobs are triggered by program args). Commented Dec 8, 2021 at 8:43

1 Answer 1

2

I could manage it by adding an additional @EnableAutoConfiguration that is only executed on a certain condition. This way I can dynamically exclude the database config, while keeping a clean basis main @SpringBootConfiguration class.

public class DataSourceConfig {
    @Configuration
    @Conditional(MyCondition.class)
    @EnableAutoConfiguration(exclude = {
            DataSourceAutoConfiguration.class,
            DataSourceTransactionManagerAutoConfiguration.class,
            HibernateJpaAutoConfiguration.class})
    static class ExcludeDataSource {
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.