(三十)在Spring配置JDBC操作

        如果想要简化整个JdbcTemplate的操作流程,那么唯一可以进行的方式就是利用配置文件采用依赖注入的方式实现操作.下面也实现同样的操作,但是尽量使用一种更为合理的做法,如果真的在实际开发之中,使用了JdbcTemplate,那么也只会在数据层上使用.

范例:定义INewsDAO接口

package cn.zwb.dao;

import cn.zwb.vo.News;

public interface INewsDAO {
	public boolean doCreate(News vo) throws Exception;
}	

范例:实现INewsDAO接口

package cn.zwb.dao.imppl;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import cn.zwb.dao.INewsDAO;
import cn.zwb.vo.News;
@Component
public class NewsDAOImpl implements INewsDAO{
	private JdbcTemplate jt;
	@Autowired  //自动根据匹配类型注入所需要的数据
	public NewsDAOImpl(JdbcTemplate jt) {
		this.jt=jt;
	}
	@Override
	public boolean doCreate(News vo) throws Exception {
		final String sql="insert into news(title,pubdate,content) values(?,?,?)";
		int count=jt.update(sql,vo.getTitle(),vo.getPubDate(),vo.getContent());
		return count>0?true:false;
	}
	
}

        现在的关键就在于applicationContext.xml文件.

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
	<context:annotation-config/>
	<context:component-scan base-package="cn.zwb"/>
	<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/aaa"/>
		<property name="username" value="root"/>
		<property name="password" value="123456"></property>
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<constructor-arg name="dataSource" ref="dataSource"/>
	</bean>
</beans>

        那么此时JdbcTemplate类与DataSource之间的关系就通过配置文件搭配完成;

范例:编写测试代码

package cn.zwb.demo;
import java.util.Date;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import cn.zwb.dao.INewsDAO;
import cn.zwb.vo.News;

public class TestSpring {
	public static void main(String[] args) throws Exception {
		ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
		INewsDAO dao=ctx.getBean("newsDAOImpl",INewsDAO.class);
		News vo=new News();
		vo.setTitle("lalalalalal");
		vo.setPubDate(new Date());
		vo.setContent("fewfewfwefwe");
		System.out.println(dao.doCreate(vo));
		
		
	}
}

        此时所有的功能都通过了Spring进行了管理,那么就表示代码几乎不需要由用户负责处理任何的辅助操作了

        

        

猜你喜欢

转载自blog.csdn.net/qq1019648709/article/details/80532876