一.在spirng容器中创建数据源连接对象
说明:本博客的操作案例是接上一篇文章的基础上进行的操作
1.1 配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--spring容器创建c3p0的连接-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/nongda"></property>
<property name="user" value="root"></property>
<property name="password" value=""></property>
</bean>
</beans>

1.2编写测试类:
@Test
//4.由spring 容器产生数据源对象
public void test4() throws SQLException {
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//2.根据id获取Bean对象
DataSource ds = ac.getBean(DataSource.class);
Connection con=ds.getConnection();
System.out.println("第四种:connection:"+con);
//3.调用类中的方法
con.close();
}

二.在spirng容器加载properties文件

2.1 配置命名空间
命名空间:xmlns:context="http://www.springframework.org/schema/context"
约束路径:http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
2.2 配置文件内容:
<?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.xsd">
<!-- 加载外部的properites文件 -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--spring容器创建c3p0的连接-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
</beans>
截图如下:

2.3 调用:


3411

被折叠的 条评论
为什么被折叠?



