Spring加载properties文件

开发时我们通常需要加载配置文件,java提供的properties文件,以键值对的方式保存信息,这篇文章记录Spring加载配置文件的方法。

一、<context:property-placeholder location=""/>标签

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

通过<context:property-placeholder location=""/>标签,可以用来加载properties配置文件,location是配置文件的路径。

<context:property-placeholder location=""/>此标签支持单个文件的加载,不过可以使用通配符,如,classpath:db*.properties,这里指定了src下的db.properties文件,那么如何使用加载的文件呢,可以使用${name},注解中我们可以这样使用:@Value("${name}")

二、propertyPlaceholderConfigurer类

<bean id="appProperty"
	class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<array>
			<value>classpath:quartz.properties</value>
			<value>classpath:db.properties</value>
		</array>
	</property>
</bean>

使用这种方式可以指定多个properties文件,只要配置多个<value>标签即可,这种方式和<context:property-placeholder />标签方式使用是一样的。

<context:property-placeholder location=""/>和配置PropertyPlaceholderConfigurer类的方式在spring的配置文件中只有一个起作用,即,假如都配置了,只有最先配置的才会被配置文件加载到,因为spring容器采用反射扫描机制,如果已经有一个PropertyPlaceholderConfigurer类的实例,那么就不会再创建了,因此使用其中一种方式即可。

三、PropertiesFactoryBean类

<bean id="configProperties"
	class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	<property name="locations">
		<list>
			<value>classpath:quartz.properties</value>
			<value>classpath:db.properties</value>
		</list>
	</property>
</bean>
要使用这种方式加载的properties文件,需要使用 #{beanId['键']},如上面的, #{configProperties['namel']},主要这里使用的是#不是上面使用的$。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值