1.建立一个项目,导入jar包(ioc aop dao 连接池 数据库驱动包)拷贝Spring容器对应的配置文件到src下
2.在配置文件中引入外部属性文件
3.配置数据源
4.配置JdbcTemplate
5.设置属性
6.测试
db.properties
1 driverClassName=oracle.jdbc.OracleDriver 2 url=jdbc:oracle:thin:@127.0.0.1:1521:xe 3 jdbc.username=[username] 4 password=[pwssword] 5 maxActive=50
最终配置的结果
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:jdbc="http://www.springframework.org/schema/jdbc" 6 xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd 7 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> 9 <!-- 引入外部属性文件 --> 10 <context:property-placeholder location="classpath:db.properties"/> 11 <!-- 配置数据源 --> 12 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 13 <property name="driverClassName" value="${driverClassName}"></property> 14 <property name="url" value="${url}"></property> 15 <property name="username" value="${jdbc.username}"></property> 16 <property name="password" value="${password}"></property> 17 </bean> 18 <!-- 配置JdbcTemplate --> 19 <bean id="jdbcTemlate" class="org.springframework.jdbc.core.JdbcTemplate"> 20 <!-- 设置属性 --> 21 <property name="dataSource" ref="dataSource"></property> 22 </bean> 23 </beans>
测试
1 package com.xcz.test; 2 3 4 import java.sql.Connection; 5 import java.sql.SQLException; 6 7 import javax.sql.DataSource; 8 9 import org.junit.jupiter.api.Test; 10 import org.springframework.context.ApplicationContext; 11 import org.springframework.context.support.ClassPathXmlApplicationContext; 12 13 class JdbcTest { 14 //实例化IOC容器对象 15 ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml"); 16 @Test 17 void test() throws SQLException { 18 DataSource dataSource = (DataSource) ioc.getBean("dataSource"); 19 System.out.println(dataSource.getConnection()); 20 } 21 }
注意:在配置的时候,给db.properties里的username前面加上jdbc,为了区分,避免和系统用户冲突导致一直报用户名or密码错误
出现这个就说明配置成功