Spring加載Properties配置文件的幾種方式


 

一:通過context:property-placeholder標簽實現配置文件加載

在spring的配置文件中添加如下聲明

<context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties"/>

 

引用值時,注意使用$引用需要的值
1.在datasource.xml中

<!-- 配置數據源 -->
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />

2.在java代碼中

@Value("${targetVal}")  
private String targetVal; // 注意:這里變量不能定義成static

 

二:通過 util:properties 標簽實現配置文件加載

在spring的配置文件中添加如下聲明

<util:properties id="jdbc" local-override="true" location="classpath:jdbc.properties"/>

需要注意幾點,這種方式需要在spring配置文件頭部進行如下聲明

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.2.xsd"

 

在引用值時,注意使用#
1.在xml中使用

<property name="username" value="#{jdbc['jdbc.username']}" />
<property name="password" value="#{jdbc['jdbc.password']}" />

2.在java代碼中

@Value(value="#{jdbc['targetVal']}")
private String targetVal;

 

三、通過 @PropertySource 注解實現配置文件加載

在java類文件中使用 PropertySource 注解:

@PropertySource(value={"classpath:jdbc.properties"})
public class ReadProperties {

    @Value(value="${jdbc.username}")
    private String username;

}

四、通過 PropertyPlaceholderConfigurer 類讀取配置文件

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>/WEB-INF/mail.properties</value>  
            <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean>

取值與方法一相同

五:使用 PropertiesFactoryBean 加載

<bean id="propertiesReader" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath*:/conf/application.properties</value>
            <value>classpath*:/conf/streamserver.properties</value>
        </list>
    </property>
</bean>

取值與方法二相同

以上是常見的取值方式,下一篇將會介紹context:property-placeholder常用的屬性

 

 

轉 : https://blog.csdn.net/Cool_Coding/article/details/90617687

 


免責聲明!

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



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