A configuration class is a Java class that supplies configuration to Spring. Mark it with @Configuration to tell Spring that it can provide beans to the application context—the place where Spring manages application components. Use explicit configuration when Spring cannot configure what you need automatically. section 1.1
@Configuration
public class ServiceConfiguration {
@Bean
public InventoryService inventoryService() {
return new InventoryService();
}
@Bean
public ProductService productService() {
return new ProductService(inventoryService());
}
}
In this service example, @Bean marks each method’s return value for addition to the application context. The ProductService method passes the InventoryService returned by inventoryService() to its constructor. By default, the bean IDs match the method names. section 1.1
Configuration classes can also hold web configuration. If the home page only needs to forward a GET request for “/” to a view, a view controller can replace a dedicated controller class. section 2.4
Listing 2.16 Declaring a view controller
package tacos.web;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("home");
}
}
WebConfig implements WebMvcConfigurer and overrides only addViewControllers(). The registry maps “/” to the home view. That small configuration lets the application serve the same page without HomeController. section 2.4
A Spring Boot bootstrap class annotated with @SpringBootApplication is already a configuration class: its included @SpringBootConfiguration is a specialized form of @Configuration. You can put a small amount of configuration there, but a separate class for web configuration keeps the bootstrap class simple. Spring Boot’s autoconfiguration, component scanning, and autowiring reduce how much explicit configuration you need. section 1.2.2 section 2.4
