spring学习十四:配置SpringJdbc

SpringJdbc其实是JdbcTemplate,用来做数据库的操作。

现在已经用的很少了,基本都是使用Mybatis和hibernate来完成数据库的操作。

1、引入pring-jdbc依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>4.3.21.RELEASE</version>
</dependency>
<dependency>
    <groupId>commons-dbcp</groupId>
    <artifactId>commons-dbcp</artifactId>
    <version>1.4</version>
</dependency>
<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc6</artifactId>
    <version>11.2.0.2.0</version>
</dependency>

2、配置spring配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
    <!-- 读取db.properties文件 -->
    <util:properties id="dbConfig" location="classpath:db.properties"/>
    <!-- 配置连接池 -->
    <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="#{dbConfig.driver}"/>
        <property name="url" value="#{dbConfig.url}"/>
        <property name="username" value="#{dbConfig.user}"/>
        <property name="password" value="#{dbConfig.pwd}"/>
        <property name="initialSize" value="#{dbConfig.initSize}"/>
        <property name="maxActive" value="#{dbConfig.maxSize}"/>
    </bean>
    <!-- 配置jdbcTemplate(jdbc模板) -->
    <bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="ds"/>
    </bean>
</beans>

3、测试:

public class TestCase {

    private AbstractApplicationContext app;
    private JdbcTemplate jt;

    @Before
    public void before() {
        app = new ClassPathXmlApplicationContext("classpath:spring.xml");
        jt = app.getBean("jt", JdbcTemplate.class);
    }

    @After
    public void after() {
        app.close();
    }

    @Test
    public void test() {
        System.out.println(jt);
    }
}

猜你喜欢

转载自blog.csdn.net/wqh0830/article/details/86645334
今日推荐