What Is Spring Boot Auto Configuration?
This dive into auto configuration in Spring Boot covers its uses and benefits as well as an example REST service and details of how to debug it.
Join the DZone community and get the full member experience.
Join For Freelet's start with a question: why do we need spring boot auto configuration?
spring based applications have a lot of configuration.
when we use spring mvc, we need to configure a component scan, the dispatcher servlet, a view resolver, web jars (for delivering static content), among other things.
<bean
class="org.springframework.web.servlet.view.internalresourceviewresolver">
<property name="prefix">
<value>/web-inf/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources mapping="/webjars/**" location="/webjars/"/>
the following code snippet shows a typical configuration of a dispatcher servlet in a web application.
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.dispatcherservlet
</servlet-class>
<init-param>
<param-name>contextconfiglocation</param-name>
<param-value>/web-inf/todo-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
when we use hibernate/jpa, we would need to configure a datasource, an entity manager factory, a transaction manager, among a host of other things.
<bean id="datasource" class="com.mchange.v2.c3p0.combopooleddatasource"
destroy-method="close">
<property name="driverclass" value="${db.driver}" />
<property name="jdbcurl" value="${db.url}" />
<property name="user" value="${db.username}" />
<property name="password" value="${db.password}" />
</bean>
<jdbc:initialize-database data-source="datasource">
<jdbc:script location="classpath:config/schema.sql" />
<jdbc:script location="classpath:config/data.sql" />
</jdbc:initialize-database>
<bean
class="org.springframework.orm.jpa.localcontainerentitymanagerfactorybean"
id="entitymanagerfactory">
<property name="persistenceunitname" value="hsql_pu" />
<property name="datasource" ref="datasource" />
</bean>
<bean id="transactionmanager" class="org.springframework.orm.jpa.jpatransactionmanager">
<property name="entitymanagerfactory" ref="entitymanagerfactory" />
<property name="datasource" ref="datasource" />
</bean>
<tx:annotation-driven transaction-manager="transactionmanager"/>
the above examples are typical with any spring framework implementation or integration with other frameworks.
spring boot: can we think differently?
spring boot brings in a new thought process around this.
can we bring more intelligence into this? when a spring mvc jar is added into an application, can we auto configure some beans automatically?
- how about auto configuring a data source if a hibernate jar is on the classpath?
- how about auto configuring a dispatcher servlet if a spring mvc jar is on the classpath?
there would be provisions to override the default auto configuration.
spring boot looks at a) frameworks available on the classpath b) existing configuration for the application. based on these, spring boot provides basic configuration needed to configure the application with these frameworks. this is called
auto configuration
.
to understand auto configuration further, let's bootstrap a simple spring boot application using spring initializr.
creating rest services application with spring initializr
spring initializr http://start.spring.io/ is great tool to bootstrap your spring boot projects.
as shown in the image above, following steps have to be done.
- launch spring initializr and choose the following
- choose
com.in28minutes.springboot
as group - choose
student-services
as artifact - choose following dependencies
- web
- actuator
- devtools
- choose
- click generate project.
- import the project into eclipse.
- if you want to understand all the files that are part of this project, you can go here.
spring boot auto configuration in action
when we run studentservicesapplication.java as a java application, you will see a few important things in the log.
mapping servlet: 'dispatcherservlet' to [/]
mapped "{[/error]}" onto public org.springframework.http.responseentity<java.util.map<java.lang.string, java.lang.object>> org.springframework.boot.autoconfigure.web.basicerrorcontroller.error(javax.servlet.http.httpservletrequest)
mapped url path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.resourcehttprequesthandler]
the above log statements are good examples of spring boot auto configuration
in action.
as soon as we added in spring boot starter web as a dependency in our project, spring boot autoconfiguration sees that spring mvc is on the classpath. it autoconfigures dispatcherservlet, a default error page and webjars.
if you add spring boot data jpa starter, you will see that spring boot auto configuration auto configures a datasource and an entity manager.
where is spring boot auto configuration implemented?
all auto configuration logic is implemented in spring-boot-autoconfigure.jar
. all auto configuration logic for mvc, data, jms, and other frameworks is present in a single jar.
another important file inside spring-boot-autoconfigure.jar is /meta-inf/spring.factories. this file lists all the auto configuration classes that should be enabled under the enableautoconfiguration key. a few of the important auto configurations are listed below.
org.springframework.boot.autoconfigure.enableautoconfiguration=\
org.springframework.boot.autoconfigure.aop.aopautoconfiguration,\
org.springframework.boot.autoconfigure.messagesourceautoconfiguration,\
org.springframework.boot.autoconfigure.propertyplaceholderautoconfiguration,\
org.springframework.boot.autoconfigure.jackson.jacksonautoconfiguration,\
org.springframework.boot.autoconfigure.jdbc.datasourceautoconfiguration,\
org.springframework.boot.autoconfigure.jdbc.jdbctemplateautoconfiguration,\
org.springframework.boot.autoconfigure.jdbc.jndidatasourceautoconfiguration,\
org.springframework.boot.autoconfigure.jdbc.xadatasourceautoconfiguration,\
org.springframework.boot.autoconfigure.jdbc.datasourcetransactionmanagerautoconfiguration,\
org.springframework.boot.autoconfigure.security.securityautoconfiguration,\
org.springframework.boot.autoconfigure.security.securityfilterautoconfiguration,\
org.springframework.boot.autoconfigure.web.dispatcherservletautoconfiguration,\
org.springframework.boot.autoconfigure.web.embeddedservletcontainerautoconfiguration,\
org.springframework.boot.autoconfigure.web.errormvcautoconfiguration,\
example auto configuration
we will take a look at datasourceautoconfiguration.
typically, all auto configuration classes look at other classes available in the classpath. if specific classes are available in the classpath, then configuration for that functionality is enabled through auto configuration. annotations like @conditionalonclass, @conditionalonmissingbean help in providing these features!
@conditionalonclass({ datasource.class, embeddeddatabasetype.class })
: this configuration is enabled only when these classes are available in the classpath.
@configuration
@conditionalonclass({ datasource.class, embeddeddatabasetype.class })
@enableconfigurationproperties(datasourceproperties.class)
@import({ registrar.class, datasourcepoolmetadataprovidersconfiguration.class })
public class datasourceautoconfiguration {
@conditionalonmissingbean
: this bean is configured only if there is no other bean configured with the same name.
@bean
@conditionalonmissingbean
public datasourceinitializer datasourceinitializer() {
return new datasourceinitializer();
}
embedded database is configured only if there are no beans of type datasource.class or xadatasource.class already configured.
@conditional(embeddeddatabasecondition.class)
@conditionalonmissingbean({ datasource.class, xadatasource.class })
@import(embeddeddatasourceconfiguration.class)
protected static class embeddeddatabaseconfiguration {
}
debugging auto configuration
there are two ways you can debug and find more information about auto configuration.
- turning on debug logging
- using spring boot actuator
debug logging
you can turn on debug logging by adding a simple property value to application.properties. in the example below, we are turning on debug level for all logging from org.springframework package (and sub packages).
logging.level.org.springframework: debug
when you restart the application, you will see an auto configuration report printed in the log. similar to what you see below, a report is produced including all the auto configuration classes. the report separates the positive matches from negative matches. it will show why a specific bean is auto configured and also why something is not auto configured.
=========================
auto-configuration report
=========================
positive matches:
-----------------
dispatcherservletautoconfiguration matched
- @conditionalonclass classes found: org.springframework.web.servlet.dispatcherservlet (onclasscondition)
- found web application standardservletenvironment (onwebapplicationcondition)
negative matches:
-----------------
activemqautoconfiguration did not match
- required @conditionalonclass classes not found: javax.jms.connectionfactory,org.apache.activemq.activemqconnectionfactory (onclasscondition)
aopautoconfiguration.cglibautoproxyconfiguration did not match
- @conditionalonproperty missing required properties spring.aop.proxy-target-class (onpropertycondition)
spring boot actuator
another way to debug auto configuration is to add spring boot actuator to your project. we will also add in hal browser to make things easy.
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-actuator</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.data</groupid>
<artifactid>spring-data-rest-hal-browser</artifactid>
</dependency>
hal browser auto configuration ( http://localhost:8080/actuator/#http://localhost:8080/autoconfig ) will show the details of all the beans that are auto configured and those which are not.
Published at DZone with permission of Ranga Karanam, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments