Skip to content

Lab 11: Configuration

Description

Moving hard-coded literals to an external configuration files is an important part of creating "cloud native" services.

We can also control which Spring-managed beans get loaded or used through these external properties.

Goals

  • Use @Value to load "simple" properties
  • See how to conditionally load classes based on a property

a. Simple Properties

One way to use a simple configuration property is to combine the @Value annotation using the "placeholder" notation of ${prop.name}. Let's control the currency used by the coffee order price translator.

  1. Add this field to the CoffeeOrderController:

    @Value("${order.price.currency.prefix}")
    private String currencyPrefix;
    
  2. In the CoffeeOrderResponse class, add a String parameter to the from static method called pricePrefix. Inside the from method, replace the hard-coded "$" here:

    coffeeOrderResponse.setTotalPrice("$" + coffeeOrder.totalPrice());
    

    to use the pricePrefix parameter.

  3. Back in the CoffeeOrderController, change the GET-handler method to pass the currencyPrefix value into the from method, e.g.:

    CoffeeOrderResponse.from(order.get(), currencyPrefix);
    
  4. Add the following to the application.properties file

    order.price.currency.prefix=US$
    
  5. Try it out by using cURL or Postman or similar and see how changing the configuration property affects the output.

b. Conditionally Use Advice

  1. Add the following annotation to the BadRequestControllerAdvice class:

    @ConditionalOnProperty(name = "feature.advice", havingValue = "true")
    
  2. Run the CoffeeOrderWebTest and the getNegativeIdReturnsBadRequestStatus test should now fail.

  3. Add the following property to the application.properties file:

    feature.advice=true
    
  4. Re-run the test and it should now pass.