You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring非Boot项目中Environment.getProperty返回null问题求助

问题原因

你用的<context:property-placeholder>标签会创建PropertySourcesPlaceholderConfigurer实例,它仅负责加载application.properties并解析@Value注解中的占位符,不会把这些配置属性添加到Spring的Environment对象中。这就是为什么@Value能正常取值,但environment.getProperty()返回null,且打印Environment时只看到系统属性和环境变量的核心原因。

解决方案

有两种简单方式可以让Environment加载application.properties的属性:

方案1:修改XML配置添加<context:property-source>

直接在applicationContext.xml中加入<context:property-source>标签,将配置文件属性注入到Environment中。如果需要保留@Value的解析能力,可以同时保留<context:property-placeholder>并添加ignore-unresolvable="true"避免冲突:

<context:annotation-config />
<context:property-source location="classpath:application.properties"/>
<context:property-placeholder location="classpath:application.properties" ignore-unresolvable="true"/>
<context:component-scan base-package="vd.vdourson.week4.helloWorld.service"/>

方案2:通过Java配置类加载属性

创建一个配置类,用@PropertySource注解指定配置文件路径:

@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
}

然后修改applicationContext.xml,确保扫描到这个配置类所在的包:

<context:annotation-config />
<context:component-scan base-package="vd.vdourson.week4.helloWorld.service, vd.vdourson.week4.helloWorld"/>
<context:property-placeholder location="classpath:application.properties"/>

(注意:将vd.vdourson.week4.helloWorld替换为AppConfig实际所在的包路径)

验证

修改完成后重新运行项目,打印Environment会看到新增了对应application.properties的PropertySource,此时调用environment.getProperty("NL_hello_world")或拼接后的属性名就能正常获取值。

内容的提问来源于stack exchange,提问作者vdourson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 18:46:21