@SpringBootApplication annotation, its purpose, and its usage with an example.As you may know, a Spring application typically uses the @Configuration, @ComponentScan, and @EnableAutoConfiguration annotations on the main application class to enable various Spring features.
In Spring Boot, instead of using these three annotations separately, we use the @SpringBootApplication annotation on the main application class. This single annotation combines the functionality of:
@Configurationfor Java-based Spring configuration.@ComponentScanfor component scanning.@EnableAutoConfigurationfor enabling Spring Boot's auto-configuration feature.
In short, the
@SpringBootApplication annotation combines the functionality of three Spring annotations into a single annotation.The @SpringBootApplication annotation is equivalent to the following three annotations:
@SpringBootApplication = @Configuration + @ComponentScan + @EnableAutoConfiguration
By using @SpringBootApplication, you can enable Java-based configuration, component scanning, and Spring Boot's auto-configuration with just a single annotation.
Sample Spring Boot Main Class:-
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);
}
}
@ComponentScan("com.example") annotation to scan the components in the specified package (com.example).In Spring Boot, you can override the default component scanning behavior of @SpringBootApplication by specifying the packages to scan using its parameters. For example, you can use the scanBasePackages attribute to define one or more packages that should be scanned for Spring components.
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);
}
}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
Thank you ever so for you article.Much thanks again. Want more.
ReplyDeletesalesforce billing course online
learn salesforce billing online