Spring(一)JdbcTemplate的环境搭建

时间:2023-03-08 15:36:02

1.建立一个项目,导入jar包(ioc aop dao 连接池 数据库驱动包)拷贝Spring容器对应的配置文件到src下

2.在配置文件中引入外部属性文件

3.配置数据源

4.配置JdbcTemplate

5.设置属性

6.测试

db.properties

 driverClassName=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@127.0.0.1:1521:xe
jdbc.username=[username]
password=[pwssword]
maxActive=50

db.properties

最终配置的结果

 <?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"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
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.1.xsd">
<!-- 引入外部属性文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${driverClassName}"></property>
<property name="url" value="${url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${password}"></property>
</bean>
<!-- 配置JdbcTemplate -->
<bean id="jdbcTemlate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 设置属性 -->
<property name="dataSource" ref="dataSource"></property>
</bean>
</beans>

result

测试

 package com.xcz.test;

 import java.sql.Connection;
import java.sql.SQLException; import javax.sql.DataSource; import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; class JdbcTest {
//实例化IOC容器对象
ApplicationContext ioc = new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
void test() throws SQLException {
DataSource dataSource = (DataSource) ioc.getBean("dataSource");
System.out.println(dataSource.getConnection());
}
}

test

注意:在配置的时候,给db.properties里的username前面加上jdbc,为了区分,避免和系统用户冲突导致一直报用户名or密码错误

出现这个就说明配置成功

Spring(一)JdbcTemplate的环境搭建