Spring4笔记----使用外部属性文件配置 bean

来源:互联网 发布:矩阵分解应用 编辑:程序博客网 时间:2024/05/21 10:17

在配置文件里配置 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());

}

0 0
原创粉丝点击