Spring中属性文件properties的读取与使用

在Spring容器启动时,使用内置bean对属性文件信息进行加载,在bean.xml中添加如下: 

	<!-- spring的属性加载器,加载properties文件中的属性 -->
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>/WEB-INF/configInfo.properties</value>
		</property>
		<property name="fileEncoding" value="utf-8" />
	</bean>

属性信息加载后其中一种使用方式是在其它bean定义中直接根据属性信息的key引用value,如邮件发送器bean的配置如下: 

<!-- 邮件发送 -->
	<bean id="mailSender"
		class="org.springframework.mail.javamail.JavaMailSenderImpl">
		<property name="host">
			<value>${email.host}</value>
		</property>
		<property name="port">
			<value>${email.port}</value>
		</property>
		<property name="username">
			<value>${email.username}</value>
		</property>
		<property name="password">
			<value>${email.password}</value>
		</property>
		<property name="javaMailProperties">
			<props>
				<prop key="mail.smtp.auth">true</prop>
				<prop key="sendFrom">${email.sendFrom}</prop>
			</props>
		</property>
	</bean>

另一种使用方式是在代码中获取配置的属性信息,可定义一个javabean:ConfigInfo.java,利用注解将代码中需要使用的属性信息注入;如属性文件中有如下信息需在代码中获取使用: 

#生成文件的保存路径
file.savePath = D:/test/
#生成文件的备份路径,使用后将对应文件移到该目录
file.backupPath = D:/test bak/

ConfigInfo.java 中对应代码: 

@Component("configInfo")
public class ConfigInfo {
    @Value("${file.savePath}")
    private String fileSavePath;

    @Value("${file.backupPath}")
    private String fileBakPath;
        
    public String getFileSavePath() {
        return fileSavePath;
    }

    public String getFileBakPath() {
        return fileBakPath;
    }    
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值