【SpringMVC+Spring+Mybatis整合程序之整合】

来源:互联网 发布:升腾资讯java笔试题 编辑:程序博客网 时间:2024/05/16 09:55

http://www.imooc.com/article/4833

因为每个人思路不一样,所以我在这边先分享自己的思路
对于mybatis开发持久层(DAO:DataBase Access Object 持久层访问对象)有两种。
第一种:传统的开发持久层方式即需要程序员开发持久层接口和持久层实现类
第二种:mybatis代理方式开发持久层只需要程序员提供持久层接口,既然能够对传统开发方式进行优化,
帮我们广大程序员省去了大部分工作的前提就是需要我们程序员遵循一些开发规范。
规范我这里就不说了,有忘记的回顾一下我写的mybatis的第三篇文章
既然是整合框架那我这边就不再使用原始开发持久层方式。

首先分析一下各个框架的职责:
SpringMVC:负责表现层
Service接口:处理业务
Mapper:持久层

spring负责将各层之间整合
通过Spring管理持久层的mapper(相当于Dao接口)
通过Spring管理业务层的service,service中可以调用mapper接口
Spring进行事务控制
通过Spring管理表现层handler,handler中可以调用service接口

mapper、service、handler都属于javabean

第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

第二步:整合service层
通过spring管理 service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。

第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。
没看懂?没关系再来看张图放松一下。
图片描述
这张图说明所有的组件都要在spring容器中运行。
这里要说的是不熟悉spring的同学要辛苦点看了。对于其他两个框架大部分知识点我已经在之前的文章介绍过了。
在正式动手之前先介绍一下我的开发环境:
Eclipse Indigo-j2ee-64位、JDK-1.7.0_67、Tomcat-7.0.65、Spring版本3.2、mybatis版本3.2.X、
mysql-5.5.36-win32、数据库图形化操作工具:SQLyog-10.0.0-0
几个重要的配置文件
数据库脚本文件内容:直接复制执行提交

CREATE DATABASE /*!32312 IF NOT EXISTS*/`sms` /*!40100 DEFAULT CHARACTER SET utf8 */;USE `sms`;/*Table structure for table `t_user` */DROP TABLE IF EXISTS `t_user`;CREATE TABLE `t_user` (  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '唯一标识',  `username` varchar(32) DEFAULT NULL COMMENT '用户名称',  `age` int(11) DEFAULT NULL COMMENT '用户年龄',  `gender` varchar(10) DEFAULT NULL COMMENT '用户性别',  `birthday` varchar(64) DEFAULT NULL COMMENT '用户生日',  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;

log4j.properties和数据库打交道这个文件是少不了的:

log4j.rootLogger=DEBUG, Console#Console  log4j.appender.Console=org.apache.log4j.ConsoleAppender  log4j.appender.Console.layout=org.apache.log4j.PatternLayout  log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n  log4j.logger.java.sql.ResultSet=INFO  log4j.logger.org.apache=INFO  log4j.logger.java.sql.Connection=DEBUG  log4j.logger.java.sql.Statement=DEBUG  log4j.logger.java.sql.PreparedStatement=DEBUG

还有一个db.properties文件,我先解释一下为什么要用配置文件,因为配置文件编译的成本很小,不像一个.java文件需要经历打包、测试、发布等等环节,而改动配置文件只要对应的value是正确的就可以直接丢给现场顺手使用。

jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/ssmjdbc.username=rootjdbc.password=root

导入jar包:这边我就截图了
图片描述图片描述
整体工程结构图
图片描述
重点:程序中出现的配置文件介绍以及配置
第一个文件:web.xml这个文件主要职责就是配置程序入口在这个文件中要配置上面说道的spring容器因为所有的组件都是在容器中运行的、接着要配置restful风格的url过滤器、请求参数过滤器、spring上下文监听器、以及前端控制器等等
文件内容如下:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"    id="WebApp_ID" version="2.5">    <display-name>ssm</display-name>    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list>    <!-- 加载spring容器 -->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>    </context-param>    <!-- 支持Restful风格的请求Url -->    <filter>        <filter-name>HiddenHttpMethodFilter</filter-name>        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>HiddenHttpMethodFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <!-- 过滤中文乱码 -->    <filter>        <filter-name>CharacterEncodingFilter</filter-name>        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>        <init-param>            <param-name>encoding</param-name>            <param-value>utf-8</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>CharacterEncodingFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <!-- spring容器监听器 -->    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <!-- 配置前端控制器 -->    <servlet>        <servlet-name>ssm</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <!--加载前端控制器配置文件 上下文配置位置 -->        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:spring/mvc-dispatcher-servlet.xml</param-value>        </init-param>        <!-- 随服务器启动 -->        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>ssm</servlet-name>                <!-- restful风格url -->        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>

applicationContext-dao.xml文件中主要负责配置:加载db.properties、配置数据源、配置SqlSessionFactoryBean、Mapper扫描器
内容如下:

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.2.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">        <!-- 加载db.properties文件中的内容,db.properties文件中的key要有一定的特殊规则 -->        <context:property-placeholder location="classpath:db.properties"/>        <!-- 配置数据源,使用dbcp连接池 -->        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">            <property name="driverClassName" value="${jdbc.driver}"/>            <property name="url" value="${jdbc.url}"/>            <property name="username" value="${jdbc.username}"/>            <property name="password" value="${jdbc.password}"/>            <property name="maxActive" value="30"/>            <property name="maxIdle" value="5"/>        </bean>        <!-- 配置SqlSessionFactory -->        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">            <!-- 数据源 -->            <property name="dataSource" ref="dataSource"/>            <!-- 加载mybatis的全局配置文件 -->            <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />        </bean>        <!-- 配置Mapper扫描器 -->        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">            <!-- 扫描包路径,如果需要扫描多个包中间用半角逗号隔开 -->            <property name="basePackage" value="com.hanson.ssm.mapper"/>            <!-- 这边不能使用ref="sqlSessionFactory"原因是因为上面加载配置文件导致这边引用会报错 -->            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />        </bean></beans>

applicationContext-service.xml该文件主要负责扫描业务层组件
内容如下:

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.2.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">        <!-- 扫描标注@Repository注解的service -->        <context:component-scan base-package="com.hanson.ssm.service.impl.*"/></beans>

applicationContext-transaction.xml配置文件主要负责处理事务等(这个需要了解spring AOP概念、代理模式、反射(必须要会)等技术)
文件主要内容:

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.2.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">    <!-- 事务管理器 对mybatis操作数据库事务控制,spring使用jdbc的事务控制类 -->    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">        <!-- 数据源 dataSource在applicationContext-dao.xml中配置了 -->        <property name="dataSource" ref="dataSource" />    </bean>    <!-- 通知 -->    <tx:advice id="txAdvice" transaction-manager="transactionManager">        <tx:attributes>            <!-- 传播行为 -->            <tx:method name="save*" propagation="REQUIRED" />            <tx:method name="delete*" propagation="REQUIRED" />            <tx:method name="insert*" propagation="REQUIRED" />            <tx:method name="update*" propagation="REQUIRED" />            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />        </tx:attributes>    </tx:advice>    <!-- aop -->    <aop:config>        <aop:advisor advice-ref="txAdvice"            pointcut="execution(* com.hanson.ssm.service.impl.*.*(..))" />    </aop:config></beans>

mvc-dispatcher-servlet.xml这个配置文件主要负责加载标注@Controller类、打开注解的处理器适配器、注解的处理器映射器、视图解析器等等
文件内容如下:

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xsi:schemaLocation="http://www.springframework.org/schema/beans         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd         http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd         http://www.springframework.org/schema/context         http://www.springframework.org/schema/context/spring-context-3.2.xsd         http://www.springframework.org/schema/aop         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd         http://www.springframework.org/schema/tx         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">    <!-- 组件扫描器扫描这一层组要扫描处理器 -->    <context:component-scan base-package="com.hanson.ssm.web.controller.*"></context:component-scan>    <!-- 配置注解的映射器和适配器以及其他配置 -->    <mvc:annotation-driven></mvc:annotation-driven>    <!-- 处理静态资源问题 -->    <mvc:default-servlet-handler />    <!-- 配置视图解析器 -->    <bean        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/" />        <property name="suffix" value=".jsp" />    </bean></beans>

sqlMapConfig.xml这个配置文件主要配置配置mybatis框架的一些设置例如开启二级缓存、设置pojo的别名等等
文件内容如下:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>    <!-- 全局setting配置,根据需要添加 -->    <!-- 配置别名 -->    <typeAliases>        <!-- 批量扫描设置别名 -->        <package name="com.hanson.ssm.pojo"/>    </typeAliases>    <!-- 配置Mapper        备注:由于使用Spring整合mybtais的整合包进行mapper扫描,这里不需要配置了        必须遵循:mapper.xml和mapper.java文件同名且在同一目录下        <mappers></mappers>     --></configuration>

总结:当这些文件都配置好,java类可以先只写类名加上注解,运行没有报错说明框架就被整合成功了。


作者: HansonQ 
链接:http://www.imooc.com/article/4833
来源:慕课网
1 0