Spring MVC 屬性文件讀取注入到靜態字段


 

在項目中,有些參數需要配置到屬性文件xxx.properties中,這樣做是為了維護方便,如果需要變動只需修改屬性文件,不需要重新編譯項目就可以了,非常方便。

而為了使用起來方便,可以通過將屬性值注入到類的靜態字段中(static),這樣就可以用className.fieldName的方式來獲取了。

1.servlet-context.xml

 <!-- spring的屬性加載器,加載properties文件中的屬性 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:config.properties" /> </bean> <context:component-scan base-package="com.jykj.demo.util" /> 

 

注意: 這里需要配置spring自動掃描的包名,該包下包含了需要被注解的類ConfigInfo

2. config.properties (示例屬性)

admin_id=1 default_password=888888

3.ConfigInfo (對應的配置bean)

package com.jykj.demo.util; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class ConfigInfo { public static int admin_id; public static String default_password; //屬性配置文件 @Value("${admin_id}") public void setAdmin_id(int admin_id) { ConfigInfo.admin_id = admin_id; } @Value("${default_password}") public void setDefault_password(String default_password) { ConfigInfo.default_password = default_password; } } 

 

注意: 這里需要將自動生成setter的方法的修飾符static去掉,否則spring無法注入

4. 使用

在任何類中直接使用 ConfigInfo.xxx 即可方便引用,如 ConfigInfo.default_password

這個雖然簡單,但我花了很久的時間從網上找尋各種解決方案,所以有必要寫下來,這樣可以方便以后盡快找到答案不要浪費時間。

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM