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

