2013-02-23 65 views
0

我想將屬性文件(.properties)加載到我的類中,我在此處的另一個線程中遵循示例:How to read values from properties file? - 但它不適用於我。將屬性文件加載到Spring中的類

這裏是我的快速實施:

的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> 
<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" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xsi:schemaLocation=" 
    http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 


    <context:annotation-config /> 

    <!-- Load up properties --> 
    <context:component-scan base-package="com.test"/> 
    <context:property-placeholder location="file:///C:/dev/workspace/test-project/src/main/resources/appconfig.properties"/> 
</beans> 

TestConfig.java

@Component 
public class TestConfig 
{ 

    @Value("${test.key1}") 
    private String key1; 

    public String getKey1() 
    { 
     return key1; 
    } 

} 

的src /主/資源/ appconfig.properties

test.key1=value 
test.key2=value 

開始了我的tomcat,我看到在我的日誌如下:

00:11:41,985 [localhost-startStop-1] INFO PropertyPlaceholderConfigurer - Loading properties file from URL [file:/C:/dev/workspace/test-project/src/main/resources/appconfig.properties] 

然而,當我做getKey1(),我得到 「空」。

我錯過了什麼?

問題2:如果我使用 「類路徑」:

<context:property-placeholder location="classpath:appconfig.properties"/> 

哪個目錄是指什麼? WEB-INF/classes的根目錄?

回答

0

這很愚蠢......

當我拿到TestConfig對象,我是這樣做的:

TestConfig config = new TestConfig(); 
config.getKey1(); 

這當然配置對象是一個全新的對象,從來沒有實例化(或注射)與任何東西。

相反,我注入它,所以它得到了由Spring框架初始化:

@Autowired 
private TestConfig config; 
0

我希望你能像Eclipse一樣使用IDE。

  • 檢查資源目錄添加到類路徑,它包括所有的文件中一樣好,如果日食必須添加中列入模式

  • 生成項目並檢查屬性文件可在WEB-INF/classes

要回答你的第二個問題

classpath:appconfig.properties是的春天將查找在文件WEB-INF/classes

+0

我 - 它失敗的第一個,它是使用本地計算機的file://引用。我使用Maven構建項目並將其部署到Tomcat 7.我檢查了生成的war,並且在\ WEB-INF \ classes – 2013-02-23 05:44:59

+0

中有appconfig.properties,感謝編輯,所以即使我使用classpath:appconfig。屬性,它應該是好的,因爲屬性文件在war文件中。所以不知何故我的@Component類沒有初始化? – 2013-02-23 13:30:07

相關問題