Understand @SpringBootApplication Annotation

What is @SpringBootApplication Annotation?

When we develop a Spring Boot application we see our main class annotated with @SpringBootApplication.

The below code will look familiar to Spring Boot developers, as this is the syntax of our main class.

@SpringBootApplication
public class BikeApplication {

public static void main(String[] args) {

      SpringApplication.run(BikeApplication.class, args);

  }
}

Let’s try to break down what @SpringBootApplication does. This annotation is a combination of 3 annotations:

@SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiguration

  1. @Configuration
  2. @ComponentScan
  3. @EnableAutoConfiguration

@Configuration
Java-based configuration: No need for XML based configuration in spring boot.
This makes a class to be eligible as Configuration class for Spring Container to understand.

@ComponentScan

Spring Boot autodiscovery feature is magic. Remember Spring MVC’s way of component scan.

we needed to explicitly mention the packages in which our component classes were present either in XML or in java based.

Spring Boot automatically discovers all classes which are present in the package in which the main class is present and its sub packages.

Example-

com.demo (main class)
com.demo.controller (all controller classes)
com.demo.service (all service classes)
com.demo.repository (all repository classes)

Here automatically all classes are autodiscovered via @ComponentScan feature of spring boot.

Note:- All the classes and packages should be under the main class package for spring boot to auto-configure the other classes.

@EnableAutoConfiguration
Remember Spring MVC world to even run a simple hello world application you needed to set up,

  1. dispatcher servlet in web.xml
  2. Mention all beans in the configuration file and set up view resolver to resolve view.

Spring Boot makes use of common sense like humans it assumes that as you are developing a web-based application you will need dispatcher servlet and view resolver.

so it automatically configures dispatcher servlet and automatically files in src/main/resources/template get resolved.

Check below link to see how there is no need to set up a view resolver.

Hello World application in spring boot using controller and thymeleaf

I hope now you have a good understanding of @SpringbootApplication Annotation. Why we use it and how to use it.

If you have any query please leave us a comment.

You may also like...

Leave a Reply

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