您的位置:首页 > 编程语言 > Java开发

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());

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: