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.
-
Add this field to the
CoffeeOrderController
:@Value("${order.price.currency.prefix}") private String currencyPrefix;
-
In the
CoffeeOrderResponse
class, add aString
parameter to thefrom
static method calledpricePrefix
. Inside thefrom
method, replace the hard-coded"$"
here:coffeeOrderResponse.setTotalPrice("$" + coffeeOrder.totalPrice());
to use the
pricePrefix
parameter. -
Back in the
CoffeeOrderController
, change the GET-handler method to pass thecurrencyPrefix
value into thefrom
method, e.g.:CoffeeOrderResponse.from(order.get(), currencyPrefix);
-
Add the following to the
application.properties
fileorder.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
BadRequestControllerAdvice
class:@ConditionalOnProperty(name = "feature.advice", havingValue = "true")
-
Run the
CoffeeOrderWebTest
and thegetNegativeIdReturnsBadRequestStatus
test should now fail. -
Add the following property to the
application.properties
file: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