你好,游客 登录 注册 搜索
背景:
阅读新闻

Spring基础—— 在 Spring Config 中使用外部属性文件

[日期:2016-07-19] 来源:Linux社区  作者:solverpeng [字体:大 中 小]

一、在 Spring Config 文件中配置 Bean 时,有时候需要在 Bean 的配置里添加 系统部署的细节信息, 如文件路径,数据源配置信息。而这些部署细节实际上需要在配置文件外部来定义。

二、Spring 提供了一个 PropertyPlaceholderConfigurer 的 BeanFactory 后置处理器。这个处理器允许用户将 Bean 的配置部分内容外移到属性文件中,然后可以在 Bean 的配置文件

里使用形式为 ${var}的变量,PropertyPlaceholderConfigurer 从属性文件里加载属性,并使用这些属性来替换变量。

三、Spring 还允许在属性文件中使用 ${key},以属性间的互相引用。

四、使用:需要注册 PropertyPlaceholderConfigurer 。通过 <context:property-placeholder location="props.properties"/> 这种方式来指定属性文件。

五、例子:

1.目录结构

Spring基础—— 在 Spring Config 中使用外部属性文件

2. spring-config.xml

<context:property-placeholder location="db.properties"/>
<bean class="com.linuxidc.spring.bean.Employee" id="employee" p:empName="${abc}" p:age="${cde}" scope="prototype"/>

3.db.properties

abc=123456
cde=${abc}

4.测试

@Test
public void test01() {
  Employee employee = ctx.getBean(Employee.class);
  System.out.println(employee);
}

5.控制台输出

Employee{empName='123456', age=123456}

Spring中如何配置Hibernate事务 http://www.linuxidc.com/Linux/2013-12/93681.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基于 Spring 设计并实现 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成实例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 进行单元测试 http://www.linuxidc.com/Linux/2013-09/89913.htm

运用Spring注解实现Netty服务器端UDP应用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企业应用开发实战 PDF完整高清扫描版+源代码 http://www.linuxidc.com/Linux/2013-10/91357.htm

Spring 的详细介绍:请点这里
Spring 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-07/133312.htm

linux
相关资讯       Spring基础  Spring Config 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款