Monday, December 2, 2019

How Spring Boot Works Internally || Spring Boot Initialization Steps

Below is the description of Spring Boot initialization steps that eventually register DispatcherServlet.

Example Code
@EnableAutoConfiguration
public class TestSpring {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(TestSpring.class, args);
    }
}
Spring Boot Initialization Steps
Here are the steps:

SpringApplication.run() creates EmbeddedWebApplicationContext application context;
Calls its refresh() method;
Refresh process reads annotations of the starting class TestSpring. It looks for import annotations. EnableAutoConfiguration is one of them. For an import annotation the refresh process gets the corresponding class from the annotation value and invokes its selectImports() method;
In case of @EnableAutoConfiguration the corresponding class is EnableAutoConfigurationImportSelector whose selectImports() loads tons of other import selectors from the META-INF/spring.factories;
This process continues recursively. Also, all bean definitions, that are inside these import selectors, are read. I.e. it includes beans defined by a method with the @Bean annotation, i.e. beans that require the Spring context to call the corresponding method automatically to instantiate them;
The resfresh() continues and reaches onRefresh(), the createEmbeddedServletContainer() method is called inside;
Among read bean defitions at the previous step, beans implementing ServletContextInitializer are searched for and instantiated. One of them is the bean, defined by the DispatcherServletAutoConfiguration.DispatcherServletRegistrationConfiguration#dispatcherServletRegistration() method of ServletRegistrationBean type that extends ServletContextInitializer. As you can guess from the name of the class, such initializers add a given servlet (in this case DispatcherServlet) to a given ServletContext, when their onStartup() method is invoked;
A tomcat embedded server is created (not started completely yet). All found ServletContextInitializers at the previous step are passed to this tomcat initialization - this is where the onStartup() methods of those ServletContextInitializers are called and DispatcherServlet gets created and registered as servlet;
End of onRefresh() of application context;
The finishRefresh() is called where tomcat is finally started by TomcatEmbeddedServletContainer.start();
End of refresh() of application context and other final initialization steps;
The app is running.

After this read the following :


https://sivalabs.in/2016/03/how-springboot-autoconfiguration-magic/

https://medium.com/codeshake/spring-boot-auto-configuration-mystery-revealed-d734516dddfb

No comments:

Post a Comment