A Spring bean is an application component created and managed by the Spring application context. The context also connects beans that need one another, forming a working application. section 1.1
These connections use dependency injection: instead of creating and managing its own dependencies, a bean receives them from the container, typically through constructor arguments or property accessor methods. section 1.1
Wiring two services
A product service needs an inventory service to provide complete product information. The application context creates both services and supplies the inventory service to the product service. section 1.1
@Configuration
public class ServiceConfiguration {
@Bean
public InventoryService inventoryService() {
return new InventoryService();
}
@Bean
public ProductService productService() {
return new ProductService(inventoryService());
}
}
This Java configuration declares both services with @Bean methods. The product service is constructed with the inventory service it needs. section 1.1
Beans can also be declared in XML, discovered through component scanning, or configured automatically by Spring Boot. For example, @Controller identifies a class for scanning; Spring discovers it and creates a bean. Other scanning annotations include @Component, @Service, and @Repository. section 1.5 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
}
}
This controller is discovered as a bean. Its @GetMapping method handles requests for the root path and returns the logical view name home. section 1.3.1
Spring Boot autoconfiguration can configure infrastructure beans too. With the Web and Thymeleaf starters, it configures beans for Spring MVC, embedded Tomcat, and a Thymeleaf view resolver. section 1.3.6
For monitoring, a bean can be exposed as a JMX MBean with @ManagedResource. Its methods and properties can be exposed with @ManagedOperation and @ManagedAttribute. section 17.4




