1. 不加载*.properties时
applicationContext.xml(druid)代码:
//name的值为,原本dataSource的set方法后面的值
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/test"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
2. 加载*.properties时
applicationContext.xml(c3p0)代码:
##重点加上: xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
- 主要是xmlns="http://www.springframework.org/schema/beans"中的beans换成context,前面加个冒号和context
- xsi:schemaLocation=“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd”>中的beans换成context
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<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>
test.java 代码:
@Test
//测试Spring容器产生druid数据源对象
public void test5() throws SQLException{
ApplicationContext app = new ClassPathXmlApplicationContext("application.xml");
DruidDataSource druidDataSource = app.getBean(DruidDataSource.class);
DruidPooledConnection connection = druidDataSource.getConnection();
System.out.println(connection);
connection.close();
}