(五)spring配置文件--使用外部属性文件
2017-10-19 15:58
531 查看
第一步:数据源配置信息
建立db.properties文件,配置数据源信息
user=root
password=root
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///test
第二步:配置bean文件
第三步:运行main方法
第四步:运行结果 数据源链接成功
c3p0com.mchange.v2.c3p0.impl.NewProxyConnection@b9cca6
建立db.properties文件,配置数据源信息
user=root
password=root
driverclass=com.mysql.jdbc.Driver
jdbcurl=jdbc:mysql:///test
第二步:配置bean文件
<?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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 导入属性文件 1.在配置文件中配置Bean时,有时需要在Bean的配置里混入系统部署的细节信息(例如:文件路径,数据源配置信息等)而这些部署细节实际上需要和Bean配置相分离 2.Spring提供了一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分内容外移到属性文件中。 可以在Bean配置里使用${var}获取属性值;PropertyPlaceholderConfigurer从属性文件里加载属性并使用这些属性来替换变量 --> <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="driverClass" value="${driverclass}"></property> <property name="jdbcUrl" value="${jdbcurl}"></property> </bean> </beans>
第三步:运行main方法
package com.atguigu.spring.beans.properties; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main { public static void main(String[] args) throws SQLException { ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-properties.xml"); DataSource dataSource=(DataSource) ctx.getBean("dataSource"); System.out.println("c3p0"+dataSource.getConnection()); } }
第四步:运行结果 数据源链接成功
c3p0com.mchange.v2.c3p0.impl.NewProxyConnection@b9cca6
相关文章推荐
- Spring4笔记----使用外部属性文件配置 bean
- [原创]java WEB学习笔记99:Spring学习---Spring Bean配置:自动装配,配置bean之间的关系(继承/依赖),bean的作用域(singleton,prototype,web环境作用域),使用外部属性文件
- Spring-Bean配置-使用外部属性文件
- 【跟我学spring 4.0 】之第七节-spring使用外部属性文件-spring配置连接oracle数据库
- Spring4深入理解IOC&DI02----Bean配置--自动装配、bean之间的继承与依赖、使用外部属性文件
- Spring中配置bean时使用外部属性文件
- spring 使用外部配置文件访问数据库
- Spring---Bean使用外部属性文件
- Spring中使用Map、Set、List、数组、属性集合的注入方法配置文件
- Spring 学习笔记 8. 尚硅谷_佟刚_Spring_使用外部属性文件
- Spring使用外部的配置文件
- spring(9) Spring中使用外部属性文件
- JdbcTemplae使用入门&&Spring三种连接池配置&&Spring配置文件引用外部properties文件
- 关于 Spring 中使用 context:property-placeholder 属性占位符设置配置文件
- spring管理属性配置文件properties——使用PropertiesFactoryBean
- 让spring的配置文件可以使用外部properties里的参数。
- Spring IOC使用外部属性文件
- spring中使用外部属性文件(关于PropertyPlaceholderConfigurer)
- spring4学习:使用外部属性文件