Spring Boot Auto Configuration

@SpringBootApplication – this annotation initializes Spring (Component Scan) and Spring Boot (Auto Configuration).

  • this annotation indicates that the class is a Spring context file. Nothing but Java configuration.
  • It enables, component scan.
  • It enables, auto configuration.

Class annotated with @RestController would be registered as a component or Bean and would be managed by Spring Framework.

SpringApplication.run() method is used to launch Spring Boot application.
To the method, we give Spring context as an input. Here, we are giving, the class which is annotated with @SpringBootApplication as spring context.

@SpringBootApplication
public class HelloSpringBootApplication {
    public static void main(String[] args) { 
       ApplicationContext context = 
          SpringApplication.run(HelloSpringBootApplication.class, args); 
          for (String name : context.getBeanDefinitionNames()) { 
             System.out.println(name); 
          }
    }
}

run( ) method returns ApplicationContext.

If you print all the beans context.getBeanDefinitionNames() loaded by Spring Framework, you can see a lot of beans created by Spring. There are lot of things that are getting configured for us automatically. This is because of auto-configuration.

How ??

As part of Spring Boot Framework, there is something called spring-boot-autoconfigure  dependency. This dependency has a lot of logic built into it and there a lot of classes present in this dependency. These auto configuration classes are creating these beans. You can check this :

spring-boot-autoconfigure-2.0.0.M4.jar :
     META-INF\spring.factories; 
     META-INF\spring-autoconfigure-metadata.properties

At the start up, Spring Boot Framework would trigger the spring-boot-auto-configure JAR. And then, it would look through classes which are on the classpath.

Spring Boot looks at :

  • Frameworks available on the CLASSPATH
  • 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.

 

Debugging Auto Configuration :

There are two ways you can debug and find more about auto configuration :

  • Turning on debug logging
  • Using Spring Boot Actuator

Debug Logging :

You can turn debug logging by adding a simple property value to application.properties file. 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 would see an auto configuration report printed in the log.