简体   繁体   中英

spring boot autoconfiguration include

Is there a way to include autoconfigurations based on profiles? (It would be nice if there was a spring.autonfigure.include )

I would like to connect to an h2 database for testing and for local development. For ease of development, I would like DataSourceAutoConfiguration.class , HibernateJpaAutoConfiguration.class , and DataSourceTransactionManagerAutoConfiguration.class autoconfigured. However, I would like to be able to easily switch to an oracle database which is defined in the application server and configured in a Configuration class. When switching to the oracle database, I need to exclude the autoconfiguration classes above:

// This only works for the oracle database - need to include autoconfig
// classes for h2 database
@SpringBootApplication(
     exclude = {
       DataSourceAutoConfiguration.class,
       HibernateJpaAutoConfiguration.class,
       DataSourceTransactionManagerAutoConfiguration.class },
     scanBasePackages = {
       "foo.bar"
     })

I have an "h2" profile that configures the h2 database and several other profiles in which I want the live database (local, dev, test, qual, prod). I could use the spring.autoconfigure.exclude property on each of the live database profiles, but sometimes I want to switch between "live" and h2 databases locally. I could also figure out exactly what the excluded autoconfigure classes are doing and manually configure in an "h2" profile but I'd rather not duplicate effort.

Anyone have ideas as to how to accomplish this?

I was able to get this to work by splitting up the @SpringBootApplication annotation and providing specific @EnableAutoConfiguration annotations.

@Configuration
@ComponentScan(basePackages = {"foo.bar"})
@EnableTransactionManagement
@EnableConfigurationProperties
public class App extends SpringBootServletInitializer {
    public static void main(String... args) throws Exception {
        SpringApplication.run(App.class, args);
    }
}

For the h2 database, I enable the "h2" profile and use this class:

@Profile("h2")
@Configuration
@EnableAutoConfiguration
public class H2Config {
    @Bean
    public ServletRegistrationBean h2servletRegistration() {
        ServletRegistrationBean registration = new ServletRegistrationBean(new WebServlet());
        registration.addUrlMappings("/console/*");
        return registration;
    }
}

And for the "live" oracle database, I disable the "h2" profile and use this class:

@Profile("!h2")
@Configuration
@EnableAutoConfiguration(exclude = {
        DataSourceAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class,
        DataSourceTransactionManagerAutoConfiguration.class })
public class NonH2Config {

}

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