我想將屬性文件(.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的根目錄?
我 - 它失敗的第一個,它是使用本地計算機的file://引用。我使用Maven構建項目並將其部署到Tomcat 7.我檢查了生成的war,並且在\ WEB-INF \ classes – 2013-02-23 05:44:59
中有appconfig.properties,感謝編輯,所以即使我使用classpath:appconfig。屬性,它應該是好的,因爲屬性文件在war文件中。所以不知何故我的@Component類沒有初始化? – 2013-02-23 13:30:07