When we create a Spring boot application we annotate it with @SpringBootApplication
annotation. This annotation 'wraps up' many other necessary annotations for the application to work. One such annotation is @ComponentScan
annotation. This annotation tells Spring to look for Spring components and configure the application to run.
Your application class needs to be top of your package hierarchy, so that Spring can scan sub-packages and find out the other required components.
package com.test.spring.boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Below code snippet works as the controller package is under com.test.spring.boot
package
package com.test.spring.boot.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@RequestMapping("/")
public String home(){
return "Hello World!";
}
}
Below code snippet does NOT Work as the controller package is NOT under com.test.spring.boot
package
package com.test.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HomeController {
@RequestMapping("/")
public String home(){
return "Hello World!";
}
}
From Spring Boot documentation:
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.
The @SpringBootApplication
annotation is equivalent to using
@Configuration
, @EnableAutoConfiguration
and @ComponentScan
with their
default attributes