Card 04/ 06

ComparisonDifficulty: Intermediate1 min

@Value vs @ConfigurationProperties

Both read from the same property sources, resolved in the same order from the previous cards. The difference is what happens when more than one related property needs to travel together.

java
@ConfigurationProperties(prefix = "pricing")
record PricingProperties(double baseFare, double perKmRate, String currency) {}
application.propertiestext
pricing.base-fare=2.50
pricing.per-km-rate=1.20
pricing.currency=USD
text
PricingProperties[baseFare=2.5, perKmRate=1.2, currency=USD]
run in a container — kebab-case in the file, camelCase in the record, bound automatically
Choosing between them
NeedReach for
One or two unrelated properties@Value("${property.name}")
A group of properties that belong together@ConfigurationProperties, bound into one typed class
A value computed with SpEL@Value, which supports expressions @ConfigurationProperties does not
Validating the properties on startup@ConfigurationProperties, which works with Bean Validation annotations on the class

Twelve related properties as twelve @Value fields scattered across a class is legal and exactly the case @ConfigurationProperties exists to replace — one prefix, one typed class, and every property that belongs together arrives together.