@ConfigurationProperties lets a Spring bean receive externally defined values from the Spring environment. A prefix connects related settings to the bean’s fields, so application behavior can change without hardcoding every value in Java code. section 6.0 section 6.2
Make the order page size configurable
An order controller can replace a hardcoded page size with a configurable property. The annotation uses the taco.orders prefix, pageSize defaults to 20, and the controller passes the injected value to PageRequest.of(0, pageSize). A YAML setting such as taco.orders.pageSize: 10 changes the result without changing the controller. section 6.2
Listing 6.1 Enabling configuration properties in OrderController
@Controller
@RequestMapping("/orders")
@SessionAttributes("order")
@ConfigurationProperties(prefix="taco.orders")
public class OrderController {
private int pageSize = 20;
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
...
@GetMapping
public String ordersForUser(
@AuthenticationPrincipal User user, Model model) {
Pageable pageable = PageRequest.of(0, pageSize);
model.addAttribute("orders",
orderRepo.findByUserOrderByPlacedAtDesc(user, pageable));
return "orderList";
}
}
Shows the annotation, prefix, default value, setter, and controller usage together. section 6.2
For cleaner design, place configuration values in a dedicated holder bean instead of coupling them to a controller. Annotate OrderProps with @Component and @ConfigurationProperties, inject it into OrderController, and reuse its values wherever needed. A holder also gives tests one focused object whose properties can be set directly. section 6.2.1
A configuration-properties bean can also:
- Read values from command-line arguments, environment variables, JVM system properties, properties files, or YAML files. section 6.0 section 6.4
- Validate injected values with @Validated, @Min, and @Max; for example, restrict pageSize to the range 5 through 25. section 6.2.1
- Work with Spring profiles to apply different property values conditionally. section 6.4
