Spring_加载Properties配置文件的几种方式详解

本文详细介绍了Spring框架中通过property-placeholder、util:properties、@PropertySource、PropertyPlaceholderConfigurer及PropertiesFactoryBean五种方式加载Properties配置文件的方法,并展示了每种方式的使用场景和注意事项。

Spring加载Properties配置文件的几种方式

一 通过context:property-placeholder标签实现配置文件加载

在spring的配置文件中添加如下声明
<context:property-placeholder ignore-unresolvable=“true” location=“classpath:jdbc.properties”/>
引用值时,注意使用$引用需要的值
在datasource.xml中

在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”
在引用值时,注意使用#
在xml中使用


在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常用的属性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吹老师个人app编程教学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值