At Value, with dollar and curly braces, reads a setting by its key. Shop name goes into a string. Shop discount is converted to an int, for us. Shop open isn't in the file, so after the colon, we give a default of true. Run it. All three values arrive, including the default.
ShopController.javajava
@RestControllerpublic class ShopController { @Value("${shop.name}") private String name; @Value("${shop.discount}") private int discount; @Value("${shop.open:true}") private boolean open; @GetMapping("/info") public String info() { return name + ": " + discount + "% off, open = " + open; }}
At Value also works on a constructor parameter. This is better, because the field can be final. Here, the discount defaults to zero, if it's missing. Run it. With ten percent off, Dune costs eight ninety nine.
PriceService.javajava
@Servicepublic class PriceService { private final int discount; public PriceService(@Value("${shop.discount:0}") int discount) { this.discount = discount; } public double sale(double price) { return Math.round(price * (100 - discount)) / 100.0; }}
Output
Dune on sale: 8.99
Also uses ShopController.java
@RestControllerpublic class ShopController { private final PriceService prices; public ShopController(PriceService prices) { this.prices = prices; } @GetMapping("/sale") public String sale() { return "Dune on sale: " + prices.sale(9.99); }}
What if a key is missing, and there's no default? Shop owner isn't in our file. Run it. The app refuses to start. It can't resolve the placeholder, shop dot owner. So always give a default, or make sure the setting exists.
ShopController.javajava
@RestControllerpublic class ShopController { @Value("${shop.owner}") private String owner; @GetMapping("/owner") public String owner() { return owner; }}
Output
ERROR SpringApplication : Application run failed
BeanCreationException: Error creating bean with name 'shopController': Injection of
autowired dependencies failed
Caused by: PlaceholderResolutionException: Could not resolve placeholder 'shop.owner' in
value "${shop.owner}"
At Value reads one setting, by key, with an optional default after a colon. A missing key, without a default, stops the app. Next, at Configuration Properties.