CodeGym /Courses /Module 5. Spring /How Spring Boot auto-configuration works

How Spring Boot auto-configuration works

Module 5. Spring
Level 4 , Lesson 2
Available

Spring Boot can auto-configure your application by looking at the libraries in the project. It's like a smart assistant: it sees a database library in the project — and immediately sets up the connection.

The idea is simple: "Got a library? We'll configure it!" Spring Boot checks which libraries are on the classpath:

  • Found a library — applied the necessary settings
  • Didn't find it — skipped it and moved on

How auto-configuration works

To understand how auto-configuration works, let's look at a simplified cycle:

  1. Scanning the application context.

    At startup Spring Boot looks at all the dependencies declared in your pom.xml (or build.gradle), and matches them against predefined conditions.

  2. Applying configuration rules.

    Spring Boot uses mechanisms described in annotations and classes to enable or disable configurations.

  3. Overriding with user settings.

    If you've set any parameters in application.properties or application.yml, they take precedence over the default auto-configuration settings.

A bit of technical detail

Auto-configuration works via the @EnableAutoConfiguration annotation (which is hidden inside @SpringBootApplication). Under the hood it looks for classes annotated with @ConditionalOnClass, @ConditionalOnMissingBean, and so on. Those annotations decide whether to include a component's configuration based on conditions.

Example: If we have Hibernate on the classpath, Spring Boot will automatically enable JPA (Java Persistence API) support and configure the EntityManager.


Example: Hibernate auto-configuration

Add a dependency for database work in pom.xml:


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

After that Spring Boot will automatically:

  • Configure the EntityManager.
  • Wire up the DataSource.
  • Set up transactions.

This configuration shows up "out of the box", without a single line of our code. All we need to do is declare entities (for example, using @Entity).


Disabling auto-configuration

Although auto-configuration is handy, sometimes it gets in the way. For example, you might want to manage database settings manually or use a specific configuration. You can disable particular parts of auto-configuration for that.

Use the @EnableAutoConfiguration annotation with an exclusion:


@SpringBootApplication(exclude = {
    DataSourceAutoConfiguration.class
})
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

Now Spring Boot won't configure the DataSource automatically. This is useful if, for example, your database is totally exotic.


Overriding auto-configuration

Spring Boot provides sensible defaults, but sometimes you need something more than "vanilla config". Want a different connection pool for the DB? Or special caching settings? You have two ways to add your own rules:

  1. Add settings to application.properties or application.yml
  2. Create your own beans that override the defaults

Spring Boot respects your choices — your settings always have priority over auto-configuration. Example: configuring DataSource via application.properties


spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

Example: overriding a bean

If auto-configuration creates a standard bean, you can replace it with your own:


@Bean
public DataSource dataSource() {
    return DataSourceBuilder.create()
        .url("jdbc:mysql://localhost:3306/mydb")
        .username("root")
        .password("secret")
        .build();
}

In that case the auto-configured DataSource will be replaced by yours.


Working with the @Conditional annotations

Spring Boot uses annotations from the org.springframework.boot.autoconfigure.condition package to flexibly control configuration. Here are a few of them:

  • @ConditionalOnClass — applies if the specified class is available on the classpath.
  • @ConditionalOnMissingBean — triggers if a bean of the same type is missing.
  • @ConditionalOnProperty — enabled if a property is set in the configuration.

Example: @ConditionalOnProperty

Let's inject conditional behavior based on configuration:

  1. In application.properties:
    
    app.feature.enabled=true
    
  2. In code:
  3. 
    @Configuration
    public class FeatureConfig {
    
        @Bean
        @ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true")
        public MyFeature myFeature() {
            return new MyFeature();
        }
    }
    

If app.feature.enabled is true, the MyFeature bean will be created. Otherwise — it won't.


Deactivating auto-configuration via spring.factories

What if auto-configuration is too pushy (or just not suitable) and you want to take control? Spring Boot keeps all of its auto-configs in the spring.factories file — it's like the remote control for auto-configuration.

Knowing this mechanism, you can either create your own auto-configuration rules or disable existing ones. Just like real life — want to control the process, find the remote.

Example of a custom spring.factories:


org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.config.MyCustomAutoConfiguration

Common mistakes and how to avoid them

  1. Duplicate configuration.

    If you specify settings both in application.properties and in Java code, it can cause conflicts. It's better to pick one configuration method.

  2. Missing dependencies.

    If the required library is missing from the classpath, auto-configuration won't kick in. Often errors happen because dependencies were forgotten in pom.xml.

  3. Accidentally disabling auto-configuration.

    Be careful with @EnableAutoConfiguration(exclude = ...) so you don't accidentally turn off too much.


Practical application

Auto-configuration helps you quickly prototype apps, which is useful both during development and in interviews. For example, if you're asked to build a REST API in 15 minutes, Spring Boot will get you there almost instantly.

In real-world development auto-configuration saves setup time, especially for standard integrations: databases, web servers, logging, security. However, for complex apps it's important to know how to tune and override it.


Now we're ready not just to use Spring Boot's magic, but to control it!

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION