[英]Injecting Properties using Spring & annotation @Value
我正在嘗試將屬性文件加載到Spring bean中,然后將該bean注入到類中。
我無法工作的唯一部分似乎是使用@Resource參考。有人可以為我連接最后一塊嗎? 我每次都得到一個空值。 似乎不想注入價值。
[編輯] - 我原本以為使用@Resource是最好的方法,但我發現的解決方案更容易。
我在另一篇文章中看到這個解決方案
參考解決方案鏈接:將 屬性值注入Spring - 由DON發布
感謝Don的帖子,但我不知道如何用@Resource完成它。
調試結果:變量值appProperties
始終為null。 它沒有被注射。
Spring Config。
樣品類:
package test;
import java.util.Properties;
import javax.annotation.Resource;
public class foo {
public foo() {}
@Resource private java.util.Properties appProperties;
}
基於以下批准的解決方案中的建議。 以下是我所做的更改。
彈簧配置:
Java類:
為了使你的解決方案工作,你還需要使foo成為一個Spring托管bean; 因為否則Spring會如何知道它必須處理你班上的任何注釋?
..class="foo"
component-scan
並指定包含foo
類的基本包。 因為我不完全確定這正是你想要的(你不想讓Spring解析一個.properties 文件並且它的鍵值對可用而不是一個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參考資料 ,因為a)這是一個很好的閱讀b)如果基礎知識清楚,你會發現Spring更容易理解。
使用屬性占位符的另一個解決方案。
春天背景:
<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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.