Spring 引入properties配置文件的方式

spring注入常量的方式,可以直接在java代碼中使用

*.properties配置文件是在開發中常用的配置文件方式,一些需要經常變動的參數會以鍵值對的方式放在其中,然後可以在*.xml文件和java代碼中直接引用,避免出現硬編碼導致違反開閉原則。而咋Spring中直接引用properties配置文件有以下幾種方式,在此記錄,權作日記。


方法一:採用配置文件<util:**>標籤方式來配置
可以對set、map、list、properties文件等類型的數據進行配置,以下以properties文件爲例說明使用方法步驟:
1、applicationContext.xml中添加
<beans xmlns:util="http://www.springframework.org/schema/util"  
xsi:schemaLocation="http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd">  
</beans>


2、使用標籤引入properties文件路徑

<util:properties id="configEnv" location="config/env.properties" />

3、在代碼中注入

@Value("#configEnv['db_key']")
private String db_key;


Tips:
1、一定要使用spring2.0以上版本方纔支持此功能
2、db_key 可以是Boolean、int、Double等其他基本類型
方法二:使用PropertyPlaceholderConfigurer方式完成配置文件載入
<bean id="appProperty"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<array>
<value>classpath:app.properties</value>
</array>
</property>
</bean>


然後使用@Value("${db_key}")直接注入使用
Tips:
1、此種方式還可以用標籤<context:property-placeholder>來代替 使用方式:
<context:property-placeholder
            ignore-resource-not-found="true"
            location="classpath*:/application.properties,
                      classpath*:/db.properties" />


location 可以一次引入多個文件
2、變量的前綴就此丟失了,因此需要在變量的key中加入前綴,以保證不會重名,一般格式:db.conn.maxConns = 30
3、此種方式注入通用性更好,可以在Spring配置文件中直接使用。如:
<bean id="dataSource" class="">
<property id="username" value="${db.oracle.username}"></property>
<property id="password" value="${db.oracle.password}"></property>
</bean>


4、還可以不通過spring配置文件而直接在程序中加載properties文件的方法,如:
context = new ClassPathXmlApplicationContext("applicationContext.xml");


PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("classpath*:/config/util.properties"));
cfg.setBeanFactory(context);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章