1. Introduction
In this quick tutorial, weβll explore two different ways to disable database auto-configuration in Spring Boot. This can come in handy when testing.
Weβll illustrate examples for Redis, MongoDB, and Spring Data JPA.
Weβll start by looking at the annotation-based approach, and then weβll look at the property file approach.
2. Disable Using Annotation
Letβs start with the MongoDB example. Weβll look at classes that need to be excluded:
@SpringBootApplication(exclude = {
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class
})
Similarly, weβll look at disabling auto-configuration for Redis:
@SpringBootApplication(exclude = {
RedisAutoConfiguration.class,
RedisRepositoryAutoConfiguration.class
})
Finally, weβll look at disabling auto-configuration for Spring Data JPA:
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
3. Disable Using Property File
We can also disable auto-configuration using the property file.
Weβll first explore it with MongoDB:
spring.autoconfigure.exclude= \
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, \
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration
Now weβll disable it for Redis:
spring.autoconfigure.exclude= \
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration, \
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration
Finally, weβll disable it for Spring Data JPA:
spring.autoconfigure.exclude= \
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration, \
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration, \
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration
4. Testing
For testing, weβll check that the Spring beans for the auto-configured classes are absent in our application context.
Weβll start with the test for MongoDB. Weβll verify if the MongoTemplate bean is absent:
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(MongoTemplate.class);
}
Now weβll check for JPA. For JPA, the DataSource bean will be absent:
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(DataSource.class);
}
Finally, for Redis, weβll check the RedisTemplate bean in our application context:
@Test(expected = NoSuchBeanDefinitionException.class)
public void givenAutoConfigDisabled_whenStarting_thenNoAutoconfiguredBeansInContext() {
context.getBean(RedisTemplate.class);
}
5. Conclusion
In this brief article, we learned how to disable Spring Boot auto-configuration for different databases.
