我在 /src/main/resources/ 下有一个属性文件,我想使用 Spring 从中加载数据。
在我的 Spring-context.xml 中我有这个:
<context:property-placeholder location="classpath:UserUtil.properties" />
还有<context:component-scan base-package="com.myApp" />
在我的类里面我加载它如下:
@Value("${injectMeThis}")
private String injectMeThis;
但该值始终为空
编辑:
要检查该值,我使用这个:
System.out.println(new myClass().getInjectMeThis());
最佳答案
System.out.println(new myClass().getInjectMeThis());
Spring只会解析@Value
它所知道的 bean 上的注释。您使用的代码在 Spring 范围之外创建该类的实例,因此 Spring 不会对其执行任何操作。
假设您已正确设置应用程序上下文 @Value
不能是null
因为这将阻止您的应用程序的正确启动。
您的 XML 文件包含 <context:component-scan />
假设myClass
是该包的一部分,最简单的解决方案是添加 @Component
至myClass
然后从上下文中检索实例而不是创建新实例。
关于java - Spring - @Value 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44542471/