Spring攻略笔记-6 外部化Bean配置

在配置文件中配置Bean时,必须记住,将部署细节如文件路径、服务器地址、用户名和密码与Bean配置混在一起是不好的做法。通常,Bean配置由应用开发人员编写,而部署细节由部署人员或系统管理员配置。


Spring有一个PropertyPlaceholderConfigurer的Bean工厂后处理器,用来将部分Bean配置外部化为一个属性文件。你可以在Bean配置文件中使用${var}形式的变量,将从属性文件中加载属性并用它们替代变量。


比如classpath下有个user.proerties文件中记录的是用户名和密码,我们需要从这个文件中获取到并配置到Bean配置文件中。

user.proerties就记录了用户名和密码

username=oracle
password=oracle

然后我们要在Bean配置文件中使用PropertyPlaceholderConfigurer,很简单,打开一个标签,指定属性文件的地址就行了。并且使用${var}的方式获取属性文件中的值

<?xml version="1.0" encoding="UTF-8"?>
<beans
	xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
						http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
						http://www.springframework.org/schema/context
						http://www.springframework.org/schema/context/spring-context-3.0.xsd
						">
	<!-- 添加注解功能 -->
	<context:annotation-config/>
	<!-- 添加自动扫描 -->
	<context:component-scan base-package="com.lkt.entity"></context:component-scan>
	
	
	<context:property-placeholder location="user.properties"/>
	
	<bean id="user" class="com.lkt.entity.User">
		<property name="username" value="${username}"></property>
		<property name="password" value="${password}"></property>
	</bean>
	
</beans>

最后我们测试下,获取一个User的实例,并打印他们的username和password,会得到oracle和oracle


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值