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 BeanConditionalOnMissingBeanβ absence of Spring BeanConditionalOnClassβ presence of class on classpathConditionalOnMissingClassβ absence of class on classpathConditionalOnCloudPlatformβ if specified cloud platform is active β for example Cloud FoundryConditionalOnExpressionβ if SpEL expression is trueConditionalOnJavaβ presence of Java in specified versionConditionalOnJndiβ if JNDI location existsConditionalOnWebApplicationβ if a web application that uses WebApplicationContext or StandardServletEnvironmentConditionalOnNotWebApplicationβ application that is not a web applicationConditionalOnPropertyβ presence of spring propertyConditionalOnResourceβ presence of resourceConditionalOnSingleCandidateβ 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>