Spring4笔记----使用外部属性文件配置 bean
2016-07-28 09:55
796 查看
在配置文件里配置 Bean 时, 有时需要在Bean
的配置里混入系统部署的细节信息(例如:文件路径、 数据源配置信息等)。 而这些部署细节实际上需要和Bean
配置相分离。
Spring 提供了一个 PropertyPlaceholderConfigurer的 BeanFactory后置处理器, 这个处理器允许用户将
Bean配置的部分内容外移到属性文件中。可以在
Bean配置文件里使用形式为 ${var} 的变量,PropertyPlaceholderConfigurer从属性文件里加载属性,
并使用这些属性来替换变量。
Spring 还允许在属性文件中使用 ${propName},以实现属性之间的相互引用。
属性文件:
user=root
password=123456
jdbcUrl=jdbc:mysql:///mybatis driver
Class=com.mysql.jdbc.Driver
配置文件:
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user"value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
</bean>
测试代码:
public void testDataSource() throws SQLException
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSourceds = (DataSource) ctx.getBean("dataSource");
System.out.println(ds.getConnection());
}
的配置里混入系统部署的细节信息(例如:文件路径、 数据源配置信息等)。 而这些部署细节实际上需要和Bean
配置相分离。
Spring 提供了一个 PropertyPlaceholderConfigurer的 BeanFactory后置处理器, 这个处理器允许用户将
Bean配置的部分内容外移到属性文件中。可以在
Bean配置文件里使用形式为 ${var} 的变量,PropertyPlaceholderConfigurer从属性文件里加载属性,
并使用这些属性来替换变量。
Spring 还允许在属性文件中使用 ${propName},以实现属性之间的相互引用。
属性文件:
user=root
password=123456
jdbcUrl=jdbc:mysql:///mybatis driver
Class=com.mysql.jdbc.Driver
配置文件:
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user"value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
</bean>
测试代码:
public void testDataSource() throws SQLException
{
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSourceds = (DataSource) ctx.getBean("dataSource");
System.out.println(ds.getConnection());
}
相关文章推荐
- Java技巧--修改Eclipse默认Workspace路径
- JAVA二进制.位运算.移位运算
- java中判断字符串是否为数字的方法的几种方法
- Spring4笔记----bean的作用范围
- java线程安全总结
- JavaEE程序猿的免费午餐③
- Spring4 Junit异常浅析
- Shiro+Spring MVC整合
- JDK配置顺序
- Myeclipse使用DB Browser连接数据库错误:OPTION SQL_SELECT_LIMIT=DEFAULT
- Spring IOC注入源码分析
- Java中Cookie的使用方法
- maven+eclipse项目问题报错原因(Cannot change version of project facet Dynamic web module to 2.5)
- java事件处理机制(自定义事件)
- Eclipse+maven 导致Eclipse启动后Build workspaces卡死或者下载缓慢的问题
- struts2自定义类型转换器
- android studio 导入eclipse项目,程序真机运行中文显示乱码
- spring整合hibernate加sqlite数据库
- 解决mac 中的myeclipse控制台中文乱码问题
- 【HDU】1250 - Hat's Fibonacci(java - BigDecimal)