Spring Boot - Disable Data Auto Configuration
We may sometimes get into a situation where we need to disable database auto-configuration, like Spring Data JPA, Mongo DB, and Redis.
We can do that in two ways - Using Annotations and Using Properties
Let's look at both the ways on each of these databases.
Using Annotations
Exclude the auto-configuration classes on @SpringBootAplication
as shown below, which disables the respective auto-configurations.
For Spring Data JPA, exclude the below classes.
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
For Mongo DB, exclude the below classes.
@SpringBootApplication(exclude = {
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class
})
For Redis, exclude the below classes.
@SpringBootApplication(exclude = {
RedisAutoConfiguration.class,
RedisRepositoryAutoConfiguration.class
})
Using Properties
Include the below properties in the application.properties
file, which disables the respective auto-configurations.
For Spring Data JPA, include the below properties.
spring.autoconfigure.exclude= \
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, \
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, \
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
For Mongo DB, include the below properties.
spring.autoconfigure.exclude= \
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, \
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration
For Redis, include the below properties.
spring.autoconfigure.exclude= \
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration, \
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration
Testing
Let's check if the existence of beans related to the auto-configuration classes, which should return NoSuchBeanDefinitionException as the respective beans are not created by the Spring automatically.
For Spring Data JPA, the below test must pass.
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(DataSource.class);
}
For Mongo DB, the below test must pass.
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(MongoTemplate.class);
}
For Redis, the below test must pass.
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(RedisTemplate.class);
}
Conclusion
Now, we know how to disable database auto-configurations on a Spring Boot application.