What happens when we call SpringApplication.run() method

SpringApplication.run() is one of the Important method used in Spring boot application. Whenever we create Spring boot application using spring.io or using STS IDE we see there is main class autogenerated and somehow it do some magic when we run the spring boot application, how come the main method initiate servlet, run the container and all that actually happened when spring boot called this main method. We will unfold this in below article about the SpringApplication.run method So lets set go!!.

Unfloading SpringApplication.run() method Image

Syntax of the class containing main method looks like code below:

public class StudentManagementApplication {

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

When we run this class as a java application then our application gets started.

Let’s try to unfold the magic which goes behind this SpringApplication.run method.

SpringApplication.run(StudentManagementApplication.class, args), is a static method it returns an object of ConfigurableApplicationContext.

ConfigurableApplicationContext ctx=SpringApplication.run(StudentManagementApplication.class, args);

Thus spring container gets started once SpringApplication.run() method is called.

Also learn: What is Spring boot Application?

Spring container once gets started is responsible for:

  1. Creating all objects: This is done by component scan remember @SpringBootApplication is a combination of @Configuration + @ComponentScan + @EnableAutoConfiguration.
  2. Dependency Injection.
  3. Managing the life cycle of all beans.

Steps Executed under this method –

So in short when the main method runs following steps occur:

  1. Application Context is started.
  2. Using application context autodiscovery occurs: @ComponentScan
  3. All default configurations are set up ie based on dependencies mentioned spring boot automatically sets up defaults. It makes use of intelligence that if we have included spring-web starter then dispatcher servlet is auto-configured. (@EnableAutoConfiguration)
  4. An embedded servlet container is started. ( No need to set up a separate web server ) . Note embedded servlet container is launched only if the web is mentioned in a dependency

Also Read: @SpringBootApplication Annotation

So, next time you run the main method, I hope you remember the magic that goes behind is application context, that’s why we recommend you to learn Spring Core as a prerequisite to Spring Boot.

Please leave us a comment if you have any issue in understanding above.





You may also like...

1 Response

  1. Anil Goyal says:

    great article….

Leave a Reply

Your email address will not be published. Required fields are marked *