Mastering Type‑Safe Configuration in Spring Boot with @ConfigurationProperties
This guide explains how to use Spring Boot's @ConfigurationProperties for type‑safe property binding, covering basic usage, custom property files, third‑party component binding, relaxed naming rules, validation, and extending support to YAML files with code examples and tests.
@ConfigurationProperties
Spring Boot’s @ConfigurationProperties annotation binds a group of properties to a Java bean, providing type‑safe configuration and avoiding the repetitive use of @Value for each property. @ConfigurationProperties(prefix = "remote") Before Spring Boot 1.5, a non‑default properties file could be loaded with the locations attribute:
@ConfigurationProperties(prefix = "remote", locations = {"classpath:remote.properties"})Example Code
Content of remote.properties:
remote.address= www.choupangxia.com
remote.port= 8080Corresponding bean:
@Component
@PropertySource({"classpath:remote.properties"})
@ConfigurationProperties(prefix = "remote")
public class RemoteConfig {
private String address;
private int port;
// getters and setters
}Controller that uses the bean:
@RestController
public class ConfigurationController {
@Resource
private RemoteConfig remoteConfig;
@GetMapping
public void getInfo() {
System.out.println("地址:" + remoteConfig.getAddress());
System.out.println("端口:" + remoteConfig.getPort());
}
}Unit test for the controller:
@SpringBootTest
@AutoConfigureMockMvc
class ConfigurationControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void getInfo() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/"));
}
}Third‑Party Component Binding
@ConfigurationProperties can also annotate a @Bean method to bind external component properties:
@Configuration
public class MyConfig {
@Bean
@ConfigurationProperties(prefix = "user")
public User user() {
return new User();
}
}Loose Binding Rules
Spring Boot applies relaxed binding, so different naming styles map to the same bean property:
user.firstName
user.first-name
user.first_name
USER_FIRST_NAMEValidation
When a bean is annotated with @Validated, JSR‑303 constraints are enforced on the bound properties:
@Component
@PropertySource({"classpath:remote.properties"})
@ConfigurationProperties(prefix = "remote")
@Validated
public class RemoteConfig {
@NotNull
private String phone;
// getters and setters
}Custom YAML PropertySource
The standard @PropertySource does not support YAML files; a custom PropertySourceFactory can be created:
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
Properties propertiesFromYaml = loadYamlIntoProperties(resource);
String sourceName = name != null ? name : resource.getResource().getFilename();
return new PropertiesPropertySource(sourceName, propertiesFromYaml);
}
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
try {
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
factory.setResources(resource.getResource());
factory.afterPropertiesSet();
return factory.getObject();
} catch (IllegalStateException e) {
Throwable cause = e.getCause();
if (cause instanceof FileNotFoundException) {
throw (FileNotFoundException) e.getCause();
}
throw e;
}
}
}Use it with @PropertySource:
@PropertySource(value = "classpath:remote.yml", factory = YamlPropertyLoaderFactory.class)Conclusion
Using @ConfigurationProperties in Spring Boot provides a clean, type‑safe way to manage simple or hierarchical configuration, supports nested beans, validation, third‑party component binding, and can be extended to handle custom YAML files.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Senior Brother's Insights
A public account focused on workplace, career growth, team management, and self-improvement. The author is the writer of books including 'SpringBoot Technology Insider' and 'Drools 8 Rule Engine: Core Technology and Practice'.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
