0 day streak
java / intermediate
Snippet

Type-safe Configuration with @ConfigurationProperties

@ConfigurationProperties provides a type-safe way to map external properties (e.g., from application.yml) into Java objects. This is superior to using @Value because it supports hierarchical structures, validation, and easier refactoring.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
@ConfigurationProperties(prefix = "app.security")
@Component
public class SecurityConfig {
private String apiKey;
private List<String> allowedOrigins;
// Getters and Setters are required
public void setApiKey(String apiKey) { this.apiKey = apiKey; }
public void setAllowedOrigins(List<String> origins) { this.allowedOrigins = origins; }
public String getApiKey() { return apiKey; }
public List<String> getAllowedOrigins() { return allowedOrigins; }
}
spring
Breakdown
1
prefix = "app.security"
Matches properties starting with this prefix in your configuration file.
2
List<String> allowedOrigins
Automatically handles comma-separated values or YAML lists into a Java List.
3
Getters and Setters
Required by Spring to bind properties to the fields of the class.