SpringTechnology

Spring Boot Auto Configuration

Quick guide to Spring Boot Auto Configuration. Learn the Spring Boot Feature with practical examples.

Spring Boot Auto-Configuration Magic | amitph

The Auto Configuration is one of the most important features of Spring Boot and seems like some magic to many newbies. Having Auto configurations, saves a lot of framework and component initialisation fuss.

What is Auto Configuration?

The Auto Configuration is an ability of Spring Boot that, analysing the declared the JAR dependencies, automatically configures a Spring Application.

Without Spring Boot

Consider a case where you want to use a spring application to query a database. You add spring-jdbc dependency to the project, as well as write XML configuration for creating datasource and jdbcTemplate.

Below is extract of an actual Spring XML configuration which creates a datasource and a jdbcTemplate.

<!-- Create Datasource -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="${app.driverClassName}"/>
    <property name="url" value="${app.url}"/>
    <property name="username" value="${app.username}"/>
    <property name="password" value="${app.password}"/>
</bean>

<!-- Load Properties -->
<context:property-placeholder location="app.properties"/>

<!-- Create JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource"/>
</bean>

You want to create a datasource instance, and the required properties are read from app.properties. Then you create a datasource by providing database connection details. Then you use the datasource reference to create a JdbcTemplate instance. If you compare any of your different projects which uses JdbcTemplate, you will see these lines of XML configurations repeated. The only thing that changes is, connection details which are part of the properties file.

What about, if the the instances are created in Java instead?
You still have repeating code.

public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(dbUsername);
    dataSource.setPassword(dbPassword);
    return dataSource;
}

public JdbcTemplate getJdbcTemplate(){
    return new JdbcTemplate(getDataSource());
}

Without Spring Boot you write too much of Boilerplate code.
You have already added dependency on spring-jdbc, then you have added driver dependency and then this boilerplate code. Spring Boot auto configuration helps getting rid of this boilerplate and let you focus on the application logic instead.

Benefits of Spring Boot Auto Configuration

The makers of Spring Boot thought differently. They identified that knowing the dependencies of the applications helps you know what the application wants. Like, when you add a dependency for jdbc, it is clear that your application wants to use a datasource instance. Spring Boot does exactly the same thing, it creates a datasource instance out of the box and makes it available instead of having application to write boilerplate to create it. Similarly, if you have an object that makes use of JdbcTemplate, Spring Boot knows and creates one for you.

Spring Boot Auto-Configuration | amitph

To achieve the auto configuration as discussed, below are the things you need to do.

Starter Dependencies

Spring Boot Starters in a bunch of dependencies which helps you get rid of finding all the various dependencies and their compatible versions. You add a certain starter dependency (for example spring-boot-starter-jdbc) with out any version. Spring Boot will download all the required Jars based on the current Spring Boot version. The respective Spring starter jar also has libraries required to auto initialise the respective components.

Application Properties

As we discussed during datasource initialisation that only connection details change application to application. Spring Boot provides a powerful properties management feature. For all the different auto configurable components Spring Boot has pre-defined set of property keys. We just need to put those keys along with values and Spring Boot knows what to do with them.

@EnableAutoConfiguration

Then you will also need to tell Spring Boot that you want to rely on its auto configuration feature. This is done by putting @EnableAutoConfigurationon your Application class or a @Configuration class. If you do not provide this annotation, Spring Boot assumes that you are going to take care of initialising the components on your own.

NOTE: @EnableAutoConfigurationis included in @SpringBootApplicationannotation and you don’t need to provide explicitly.

Spring Boot Auto Configuration Example

It’s time for you to see the auto configuration working.

Spring Boot Starter JDBC

Add Spring Boot Starter Jdbc Dependency.

For maven

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

For Gradle

compile('org.springframework.boot:spring-boot-starter-jdbc')

Application Properties

spring:
    datasource:
        driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
        password: '<password>'
        url: jdbc:sqlserver://localhost:1433;databaseName=amitph-test-db
        username: <username>

Application Class

@SpringBootApplication
public class Application implements CommandLineRunner {
    @Autowired JdbcTemplate jdbcTemplate;

    @Autowired DataSource dataSource;

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Autoconfigured JdbcTemplate = " + jdbcTemplate);
        System.out.println("Autoconfigured Datasource = "+dataSource);
    }
}

You can now run the application and see both jdbcTemplate and datasource are correctly assigned by Spring Boot.

Summary

Spring Boot Auto Configuration is a powerful feature of Spring Boot. It saves you from writing boilerplate code that is required to initialise certain components. The starter dependencies, the minimal properties helps Spring Boot know which components to auto configure.


2 thoughts on “Spring Boot Auto Configuration

Comments are closed.