Defining Custom Properties
Hardcoding absolute values (like API tokens or URL paths) uniformly directly into Java classes inherently forces you to recompile the system binary if the text changes.
Instead, developers declare arbitrary application settings structurally inside application.properties (or application.yml). Spring reads these values internally upon boot.
# Custom configuration fields
app.tax-rate=0.07
app.stripe.api-key=sk_test_12345
app.inventory.max-items=500
Reading Properties in Java
To evaluate these string constants precisely into a Java variable locally, you use the @Value annotation.
@Service
public class TaxService {
// Spring maps the application.properties value statically directly
@Value("${app.tax-rate}")
private double currentTaxRate;
// Establishing a default fallback value if completely missing
@Value("${app.inventory.max-items:100}")
private int maxItems;
public double calculateTotal(double subtotal) {
return subtotal + (subtotal * currentTaxRate);
}
}
Type Safety with @ConfigurationProperties
Using @Value hundreds of times is messy manually. You can forcefully map a hierarchical cluster of properties directly into a dedicated Java Object Class natively.
@Configuration
@ConfigurationProperties(prefix = "app.stripe")
public class StripeConfig {
// Maps directly to app.stripe.api-key internally
private String apiKey;
// Getters and Setter methods implicitly required
}