使用@Value注解读取properties文件属性返回null的解决方案求助
问题原因及解决办法
问题根源
你直接通过new Test()创建对象,这个对象不在Spring容器的管理范围内,Spring不会对它的@Value、@Configuration等注解做任何处理,所以属性值自然为null。而getProperty()是直接读取properties文件,不需要Spring的注入机制,所以能正常获取值。
解决办法
必须让Spring容器来创建并管理Test类的实例,修改main方法,通过Spring上下文加载配置类,再从容器中获取对象:
修改后的完整代码:
@Configuration @PropertySource("classpath:sample.properties") public class Test { @Value("${student.name}") private String name; public void test() { System.out.println("name = " + name); } public static void main(String args[]) { // 启动Spring注解上下文,加载Test配置类 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Test.class); // 从Spring容器中获取Test实例(此时实例已完成@Value注入) Test t = context.getBean(Test.class); t.test(); // 使用完毕关闭上下文 context.close(); } }
补充说明
如果是Spring Boot项目,也可以用SpringApplication.run启动上下文,核心逻辑一致:必须由Spring容器创建对象,才能触发@Value的属性注入流程。
内容的提问来源于stack exchange,提问作者marshmellow
相关产品推荐
相关产品推荐

