Thursday, 13 December 2018

The @SpringBootApplication Annotation usage and example

         In the current post, we will learn the @SpringBootApplication annotation usage and example. As we know that, we are using @ComponentScan, @Configuration and @EnableAutoConfiguration annotations for main class of spring class to enable the spring features.

         In spring boot, We will use the @SpringBootApplication annotation in our Application or Main class to enable a host of features, e.g. Java-based Spring configuration(@Configuration), component scanning(@ComponentScan), and in particular for enabling Spring Boot's auto-configuration feature.

     In Spring applications, we can use the following annotations as mentioned earlier,


  • @Configuration to enable Java-based configuration
  • @ComponentScan to enable component scanning.
  • @EnableAutoConfiguration to enable Spring Boot's auto-configuration feature.


        In short, I will explain the usage of @SpringBootApplication annotation,

The @SpringBootApplication annotation is a combination of following three Spring annotations and provides the functionality of all three with just one line of code.

@SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiguration


Sample Spring boot main class example,


package com.example.springbootapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication    // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {

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

}



      
       In Spring Application, we can use @ComponentScan("com.example") annotation to scan the component as mentioned in argument i.e com.example. 

       In Spring boot, you can override, with the @SpringBootApplication, the default values of component scan. You just need to include it as a parameters,

@SpringBootApplication(scanBasePackages = "com.example")

or String array(comma separated)

@SpringBootApplication(scanBasePackages = {"com.example", "com.main"})


Example:-


package com.example.springbootapp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.example")
public class Application {

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

}

In the upcoming posts, we will learn few more Spring boot annotations and examples.

Thank you for visiting blog.
Have a great day.


Related Posts:--
1) Explain advantages of Spring Boot
2) Causes and Solution of NoSuchBeanDefinitionException in Spring
3) Cause and solution of LazyInitializationException in Hibernate

1 comment: