2013-05-09 101 views
0

我使用spring 3.0.5並試圖讀取屬性文件來進行某種驗證以及數據源。但是,當我使用@Value時,我變爲null,下面是我的cfg。如何使用spring讀取屬性文件並暴露給類

在applicationContext.xml中

<bean id="propertyConfigurer" 
     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <property name="location" value="classpath:database.properties"/> 

    <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
      <property name="driverClassName" value="${jdbc.driverClassName}" /> 
      <property name="url" value="${jdbc.url}" /> 
      <property name="username" value="${jdbc.username}" /> 
      <property name="password" value="${jdbc.password}" /> 

</bean>// here It is perfectly establishing the data-source. 

我想要的暴露屬性的值文件

@Component 
public class PropertyReaderBean { 

//@Value("#{propertyConfigurer1[dailyLimit]}") 
    //@Value("#{database['jdbc.driverClassName']}") 
@Value("${jdbc.driverClassName}")// I tried all three but still getting null 
private String limit; 
public String getLimit() 
{ 
    System.out.println(" limit : "+limit); 
    return limit; 
} 

public void setLimit(String limit) { 
    System.out.println(" limit : "+this.limit); 
    this.limit = limit; 
} 

,最後databse.properties文件

的Class
jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/imps 
jdbc.username=root 
jdbc.password=root 

因此,無論何時我試圖使用上面的配置訪問值屬性文件,我變空,請指導。

更新: 然而PropertyReaderBean的setter方法不工作,我已經檢查堆棧跟蹤,但是當我在XML中添加這樣的話,我可以讀取文件的屬性值。

<bean id="propertyDao" class="com.alw.imps.validator.PropertyReaderBean"> 
      <property name="limit" value="${jdbc.password}"></property> 
     </bean> 

回答

1

一個可能的原因是@Value不起作用。您是否已經在應用程序上下文中聲明瞭<上下文:annotation-config />

+0

不,我應該需要來聲明,我使用xml聲明。 – 2013-05-09 14:41:59

+0

如果我使用基於xml的聲明,那麼註釋以及基於xml的聲明都可以工作。 – 2013-05-09 14:47:35

+0

我忘了你可能會聲明,所以不需要。 你能幫我另一個忙,以確保PropertyReaderBean和屬性佔位符在同一個應用程序上下文中,而不是在父上下文中嗎? – 2013-05-09 15:16:47

1

您不需要屬性配置器,其代碼中的定義具有語法錯誤。

您只需做到這一點,參考代碼,您有:

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

依賴於這個

xmlns:context="http://www.springframework.org/schema/context" 

http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context-3.1.xsd 
+0

做了你說的,但仍然變空 – 2013-05-09 12:33:25

+0

@arvin_codeHunk你日誌文件顯示什麼?你確定屬性文件在classapth上? – NimChimpsky 2013-05-09 12:41:52

+0

是的,因爲當我在applicationContext.xml文件中設置值時,我可以獲取bean內部的所有屬性文件值,但是當我嘗試使用註釋時,其結果爲null – 2013-05-09 13:00:48