concept @ConfigurationProperties in category spring

appears as: @ConfigurationProperties
Spring in Action, Sixth Edition

This is an excerpt from Manning's book Spring in Action, Sixth Edition.

To support property injection of configuration properties, Spring Boot provides the @ConfigurationProperties annotation. When placed on any Spring bean, it specifies that the properties of that bean can be injected from properties in the Spring environment.

To demonstrate how @ConfigurationProperties works, suppose that you’ve added the following method to OrderController to list the authenticated user’s past orders:

Spring in Action, Fifth Edition

This is an excerpt from Manning's book Spring in Action, Fifth Edition.

To support property injection of configuration properties, Spring Boot provides the @ConfigurationProperties annotation. When placed on any Spring bean, it specifies that the properties of that bean can be injected from properties in the Spring environment.

To demonstrate how @ConfigurationProperties works, suppose that you’ve added the following method to OrderController to list the authenticated user’s past orders:

Rather than hardcode the page size, you can set it with a custom configuration property. First, you need to add a new property called pageSize to OrderController and then annotate OrderController with @ConfigurationProperties as shown in the next listing.

Listing 5.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";
  }

}

The most significant change made in listing 5.1 is the addition of the @ConfigurationProperties annotation. Its prefix attribute is set to taco.orders, which means that when setting the pageSize property, you need to use a configuration property named taco.orders.pageSize.

  • Spring beans can be annotated with @ConfigurationProperties to enable injection of values from one of several property sources.