springhibernatespring-bootspring-dataspring-data-jpa

Disable all Database related auto configuration in Spring Boot


I am using Spring Boot to develop two applications, one serves as the server and other one is a client app. However, both of them are the same app that function differently based on the active profile. I am using auto configuration feature of Spring Boot to configure my applications.

I want to disable all the database related auto configuration on client app, since it won't be requiring database connection. Application should not try to establish connection with the database, nor try to use any of the Spring Data or Hibernate features. The enabling or disabling of the database auto configuration should be conditional and based on the active profile of the app.

Can I achieve this by creating two different application.properties files for respective profiles?

I tried adding this to my properties file,

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration\
  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration\
  org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration

But, the application still tries to connect to the database on start. Are those exclusions sufficient for achieving my requirement?


Solution

  • The way I would do similar thing is:

    @Configuration
    @EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
    @Profile ("client_app_profile_name")
    public class ClientAppConfiguration {
        //it can be left blank
    }
    

    Write similar one for the server app (without excludes).

    Last step is to disable Auto Configuration from main spring boot class:

    @SpringBootApplication
    public class SomeApplication extends SpringBootServletInitializer {
    
        public static void main(String[] args) {
            SpringApplication.run(SomeApplication.class);
        }
    
        protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
            return application.sources(SomeApplication.class);
        }
    }
    

    Change: @SpringBootApplication into:

    @Configuration 
    @ComponentScan
    

    This should do the job. Now, the dependencies that I excluded in the example might be incomplete. They were enough for me, but im not sure if its all to completely disable database related libraries. Check the list below to be sure:

    http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#auto-configuration-classes