Spring Boot中ConfigurationProperties无法加载值,字段全为null问题
@ConfigurationProperties配置类字段返回null问题解决(Spring 3.1.6)
问题场景
在Spring 3.1.6环境中,标记了@Configuration和@ConfigurationProperties(prefix = "end-point")的配置类,所有字段调试时显示为null,但TargetSource中存在正确的配置值。
配置类代码:
@Configuration @ConfigurationProperties(prefix = "end-point" ) public class ConfigProp { private String endpoint1; private String endpoint2; public String getEndpoint1() { return endpoint1; } public void setEndpoint1(String endpoint1) { this.endpoint1 = endpoint1; } public String getEndpoint2() { return endpoint2; } public void setEndpoint2(String endpoint2) { this.endpoint2 = endpoint2; } }
调试时代理对象的字段状态:
CGLIB$BOUND = false CGLIB$CALLBACK_0 = {CglibAopProxy$DynamicAdvisedInterceptor@11318} CGLIB$CALLBACK_1 = {CglibAopProxy$StaticUnadvisedInterceptor@11319} CGLIB$CALLBACK_2 = {CglibAopProxy$SerializableNoOp@11320} CGLIB$CALLBACK_3 = {CglibAopProxy$StaticDispatcher@11321} CGLIB$CALLBACK_4 = {CglibAopProxy$AdvisedDispatcher@11322} CGLIB$CALLBACK_5 = {CglibAopProxy$EqualsInterceptor@11323} CGLIB$CALLBACK_6 = {CglibAopProxy$HashCodeInterceptor@11324} endpoint1=null endpoint2=null
原因分析
配置类添加@Configuration后,Spring会为其生成CGLIB代理对象。@ConfigurationProperties的属性绑定逻辑仅作用于原始目标对象,代理对象自身的字段并未被赋值。直接查看代理对象的字段会显示null,但通过getter方法访问时,代理的回调逻辑会从原始目标对象中获取正确值。
解决方案
方案一:移除@Configuration注解
配置类无需标记@Configuration,改用以下方式注册并启用属性绑定:
- 给配置类添加
@Component(确保类在组件扫描路径下); - 或者在任意
@Configuration类上添加@EnableConfigurationProperties(ConfigProp.class)。
修改后的配置类示例:
@ConfigurationProperties(prefix = "end-point") @Component public class ConfigProp { // 字段、getter和setter保持不变 }
方案二:保留@Configuration,通过getter方法取值
不要直接访问配置类的字段,始终调用getter方法获取属性值。即使代理对象的字段显示为null,getter方法会通过代理回调从原始对象中返回正确的配置值。
额外检查
确认配置文件中的key与prefix匹配,例如:
end-point.endpoint1=your-endpoint-1 end-point.endpoint2=your-endpoint-2
同时确保配置文件已被Spring正确加载。
内容的提问来源于stack exchange,提问作者Chandrasekhar boya
相关产品推荐
相关产品推荐

