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
@Valueto 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.
-
Add this field to the
CoffeeOrderController:@Value("${order.price.currency.prefix}") private String currencyPrefix; -
In the
CoffeeOrderResponseclass, add aStringparameter to thefromstatic method calledpricePrefix. Inside thefrommethod, replace the hard-coded"$"here:coffeeOrderResponse.setTotalPrice("$" + coffeeOrder.totalPrice());to use the
pricePrefixparameter. -
Back in the
CoffeeOrderController, change the GET-handler method to pass thecurrencyPrefixvalue into thefrommethod, e.g.:CoffeeOrderResponse.from(order.get(), currencyPrefix); -
Add the following to the
application.propertiesfileorder.price.currency.prefix=US$ -
Try it out by using cURL or Postman or similar and see how changing the configuration property affects the output.
b. Conditionally Use Advice¶
-
Add the following annotation to the
BadRequestControllerAdviceclass:@ConditionalOnProperty(name = "feature.advice", havingValue = "true") -
Run the
CoffeeOrderWebTestand thegetNegativeIdReturnsBadRequestStatustest should now fail. -
Add the following property to the
application.propertiesfile:feature.advice=true -
Re-run the test and it should now pass.
References
The @Value annotation: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#beans-value-annotations
The Spring Expression Language: https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions
DevTools Configuration: https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-devtools-globalsettings
Conditional Configuration: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-condition-annotations