您的位置:首页 > 博客中心 > 数据库 >

Spring 开发第一步(三)Spring与JDBC

时间:2022-03-14 01:46

   《spring in action 3rd》中的前面4章讲解的是Spring的核心,也就是DI/IOC和AOP 。从第5章开始是Spring在企业开发中的各个方面的应用。其实作为笔者从事的企业计算来说,J2EE相关的最常见的内容就是如何持久化了,第5、6章讲的就是这方面的内容。

   今天主要学习了Spring与JDBC开发。

一、配置数据源

首先我们需要配置数据源,在设置好context.xml后,我们将JDBC数据源配置到Spring:

<jee:jndi-lookup id="dataSource" jndi-name="/jdbc/spitter" resource-ref="true" />  对,就这么一句话。并且id为dataSource的这个数据源可以像一个bean那样注入到另一个bean里。

比如注入到下面的DSTestBean

package com.spitter.test;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;

public class DSTestBean {
    @Autowired
    private DataSource dataSource;
    
    public void setDataSource(DataSource dataSource){
        this.dataSource = dataSource;
    }
    public DataSource getDataSource(){
        return this.dataSource;
    }
}

对应的spring配置文件如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:jee="http://www.springframework.org/schema/jee"
 xmlns:p="http://www.springframework.org/schema/p"
 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-3.0.xsd
       http://www.springframework.org/schema/aop 
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.0.xsd
       http://www.springframework.org/schema/jee 
       http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">
<!-- Beans declarariona go here -->
<context:annotation-config/>
<jee:jndi-lookup id="dataSource" jndi-name="/jdbc/spitter" resource-ref="true" />
<bean id="dsTest" class="com.spitter.test.DSTestBean" />
</beans>

注意,由于在DSTestBean中我们对dataSource属性使用了注解注入 @autowired

所以在配置文件里要加入<context:annotation-config/> ,因为Spring 默认是关闭注解装配方式的。

 二、使用Spring的template简化JDBC代码

 

 

热门排行

今日推荐

热门手游