Saturday, June 10, 2017

Spring Boot : The Magic Behind the Main Class

Lets take a closer look at the Main Class in SpringBootApplication



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

@SpringBootApplication
Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

Hence @SpringBootApplication = @ComponentScan + @Configuration + @EnableAutoConfiguration  


  • @Configuration : This annotation is not specific to the spring boot applications. This annotation tags the class as the source for bean definitions. In short, this annotation is used for defining beans using the Java configuration.
  • @EnableAutoConfiguration : This is a spring boot annotation. This annotation enables the application to add the beans using the classpath definitions.
    • org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration
    • org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration
    • many more...
       
  • @ComponentScan : This annotation tells the spring to look for other components, configurations and services in the specified path.This is equivalent to Spring XML’s < context:component-scan / >.
SpringApplication.run(...)

For more advanced configuration a SpringApplication instance can be created and customized before being run:


 public static void main(String[] args) throws Exception {
   SpringApplication app = new SpringApplication(MyApplication.class);
   // ... customize app settings here
   app.run(args)
 } 


It does the following
  1. Starts Spring 
  2. creates spring context 
  3. Applies annotations 
  4. sets up the container

No comments: