我正在尝试将属性文件加载到Spring中,然后将该bean注入到类中。
唯一我无法工作的部分似乎是使用@Resource reference.Can --有人帮我把最后一块连接起来吗?每次我都得到一个空值。似乎不想注入价值。
编辑-我最初认为使用@Resource是最好的方法,但我发现建议的解决方案更容易。
我在另一篇文章中看到了这个解决方案:
参考解决方案链接: Inject Property Value into Spring - posted by DON
这篇文章归功于唐,但我只是不知道如何用@Resource来完成它。
调试结果:变量值appProperties
始终为空。它没有被注射。
Spring Config.
样本类别:
package test;
import java.util.Properties;
import javax.annotation.Resource;
public class foo {
public foo() {}
@Resource private java.util.Properties appProperties;
}
根据下面核准的解决方案中的建议。以下是我所做的改变。
解决方案更新:
春季会议:
Java类:
发布于 2011-06-21 11:03:27
要使您的解决方案起作用,还需要将foo变成Spring托管bean;否则Spring如何知道它必须处理类上的任何注释?
..class="foo"
component-scan
的bean,并指定一个包含foo
类.的基本包。
由于我不完全确定这是否正是您想要的(您不希望.properties文件被Spring解析,并且它是可用的键值对而不是Properties
对象吗?),我建议您另一种解决方案:使用util
命名空间。
<util:properties id="props" location="classpath:com/foo/bar/props.properties"/>
并引用bean中的值(同时,必须对Spring进行管理):
@Value("#{props.foo}")
public void setFoo(String foo) {
this.foo = foo;
}
编辑:
您刚刚意识到您正在您的类中导入org.springframework.context.ApplicationContext
,这可能是不必要的。我强烈建议您至少在前几章中阅读Spring reference,因为( a)这是一个很好的阅读,b)如果基础知识是清晰的,您会发现理解Spring要容易得多。
发布于 2013-07-07 02:18:57
只有一个使用属性占位符的解决方案。
春季背景:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="your.packege" />
<context:property-placeholder location="classpath*:*.properties"/>
</beans>
要注入属性值的java类:
public class ClassWithInjectedProperty {
@Value("${props.foo}")
private String foo;
}
https://stackoverflow.com/questions/6425795
复制相似问题