DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Trending

  • SaaS in an Enterprise - An Implementation Roadmap
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • AI-Driven Root Cause Analysis in SRE: Enhancing Incident Resolution
  • Go 1.24+ Native FIPS Support for Easier Compliance
  1. DZone
  2. Coding
  3. Frameworks
  4. What Is Spring Boot Auto Configuration?

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.

By 
Ranga Karanam user avatar
Ranga Karanam
DZone Core CORE ·
May. 22, 17 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
95.2K Views

Join the DZone community and get the full member experience.

Join For Free

let'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
  • 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.

image

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.

image

image

Spring Framework Spring Boot

Published at DZone with permission of Ranga Karanam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!