使用Spring&注入属性注释@Value

时间:2011-06-21 13:13:48

标签: java spring dependency-injection

我正在尝试将属性文件加载到Spring bean中,然后将该bean注入到类中。

我无法工作的唯一部分似乎是使用 @Resource 参考。有人可以为我连接最后一块吗?我每次都得到一个空值。似乎不想注入价值。

[编辑] - 我原本以为使用 @Resource 是最好的方法,但我发现的建议解决方案更容易。

我在另一篇文章中看到了这个解决方案:

参考解决方案链接: Inject Property Value into Spring - posted by DON

感谢Don的帖子,但我不知道如何使用 @Resource 完成它。

调试结果 变量值appProperties始终为null。它没有被注射。

Spring Config。 enter image description here

样本类:

package test;

import java.util.Properties;
import javax.annotation.Resource;


public class foo {
    public foo() {}
    @Resource private java.util.Properties appProperties;
}

根据以下批准的解决方案中的建议。以下是我所做的更改。


解决方案更新:

Spring配置: enter image description here

Java类: enter image description here

2 个答案:

答案 0 :(得分:17)

为了使你的解决方案工作,你还需要使foo成为一个Spring托管bean;因为否则Spring会如何知道它必须处理你班上的任何注释?

  • 您可以在appcontext xml中将其指定为具有..class="foo"
  • 的bean
  • 或使用component-scan并指定包含foo类的基本包。

因为我不完全确定这正是你想要的(你不想让Spring解析一个.properties 文件并让它的键值对可用而不是{ {1}}对象?),我建议你另一个解决方案:使用Properties命名空间

util

引用bean中的值(也必须是Spring管理的):

<util:properties id="props" location="classpath:com/foo/bar/props.properties"/>

编辑:

刚刚意识到您要在班级中导入@Value("#{props.foo}") public void setFoo(String foo) { this.foo = foo; } ,这可能是不必要的。我强烈建议您至少在前几章阅读Spring reference,因为a)这是一个很好的阅读b)如果基础知识清楚,你会发现更容易理解Spring。

答案 1 :(得分:3)

使用属性占位符的另一个解决方案。

春天的背景:

<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;
}
相关问题