Spring Boot
August 25, 2021

M05 Q04 What things affect what Spring Boot sets up?

Spring Boot uses autoconfiguration to detect dependencies on the class path, based on detected dependencies, spring beans are configured to allow integration with technologies, like JPA, Data Sources, Embedded Databases, Template Rendering engines etc.

Spring Boot searches for META-INF/spring.factories on classpath that should contain entry org.springframework.boot.autoconfigure.EnableAutoConfiguration that lists all autoconfiguration classes provided by the autoconfiguration module.

Autoconfiguration class is using @ConditionalOn... annotations to specify under which conditions, certain Autoconfiguration should be applied.

Spring Boot provides starter modules, which are empty jars with set of dependencies specified with correct dependencies versions to allow easy start with the library

Starter module may provide only set of dependencies, or set of dependencies with autoconfiguration code.

Spring Boot supports following Conditional Annotations for AutoConfiguration classes:

  • ConditionalOnBean – presence of Spring Bean
  • ConditionalOnMissingBean – absence of Spring Bean
  • ConditionalOnClass – presence of class on classpath
  • ConditionalOnMissingClass – absence of class on classpath
  • ConditionalOnCloudPlatform – if specified cloud platform is active – for example Cloud Foundry
  • ConditionalOnExpression – if SpEL expression is true
  • ConditionalOnJava – presence of Java in specified version
  • ConditionalOnJndi – if JNDI location exists
  • ConditionalOnWebApplication – if a web application that uses WebApplicationContext or StandardServletEnvironment
  • ConditionalOnNotWebApplication – application that is not a web application
  • ConditionalOnProperty – presence of spring property
  • ConditionalOnResource – presence of resource
  • ConditionalOnSingleCandidate – only one candidate for the bean found

Let's look at the example. That's my project without any configuration class, except one ApplicationConfiguration which enables autoconfiguration and excludes data source autoconfiguration provided by Spring Boot.

Instead of Spring Boot autoconfiguration, I created my own configuration module.

What have I done? In the resource folder META-INF I added spring.factories file that contains entries with autoconfiguration classes

The first one is the configuration for embedded database. @ConditionalOnClass(name = "org.hsqldb.Database") means that if HSQL DB is available.

The next one is the configuration for JPA for datasource.

And the last this is to set dependency to configuration module in pom.xml

<dependency>
    <groupId>spring-professional-exam-tutorial-module04</groupId>
    <artifactId>module04-question04-my-autoconfiguration</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>