Component scanning lets Spring find eligible classes on an application’s classpath and create them as beans in the application context. It saves you from declaring each component in Java or XML configuration. Scanning discovers components; autowiring supplies the beans they depend on. section 1.1
In a Spring Boot application, @SpringBootApplication includes @ComponentScan, which enables scanning. It also includes @EnableAutoConfiguration, a separate feature that configures components Spring Boot thinks the application needs. SpringApplication.run() starts the application and creates its context. section 1.2.2
Listing 1.2 The Taco Cloud bootstrap class
package tacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication #1
public class TacoCloudApplication {
public static void main(String[] args) {
SpringApplication.run(TacoCloudApplication.class, args); #2
}
}
The bootstrap class shows where @SpringBootApplication enables scanning and where SpringApplication.run() starts the application. section 1.2.2
A discovered controller
Annotate a web controller with @Controller, and component scanning discovers the class and creates a bean for it. In the home-page example, @GetMapping("/") identifies the method that handles a GET request for the root path. The returned "home" names a view; it is not what makes the controller discoverable. section 1.3.1
Listing 1.4 The home page controller
package tacos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller #1
public class HomeController {
@GetMapping("/") #2
public String home() {
return "home"; #3
}
}
The controller listing separates the scanning marker, @Controller, from the request-mapping annotation, @GetMapping. section 1.3.1
Choose an annotation that describes the component’s job: @Component, @Controller, @Service, and @Repository can each mark a class for discovery. Use explicit Java or XML configuration when Spring cannot configure a component automatically. section 1.3.1 section 1.1
