手把手带你实现Spring、Spring MVC与Mybatis整合工程的搭建

系统的学完了Spring、Spring MVC以及Mybatis之后我们就可以进行这三者的整合工作了,其实不难,就是将这三个框架的配置文件提取出来放在一个项目中,然后便可以进行开发(就是这么简单)。此篇文章我们将在前篇文章Mybatis3.x与Spring3.x整合的基础上将Spring MVC的配置引入进来即可(超级简单)。

1.整合的思路

1.在Mybatis3.x与Spring3.x整合的基础上添加Spring MVC。

2.Spring要管理Spring MVC编写的Handler(controller)、Mybatis的SqlSessionFactory、mapper、数据源。

其实整合思路就是下面这三步:

  1. 第一步:整合dao(即mapper),完成Spring与Mybatis的整合。
  2. 第二步:整合service,Spring管理service接口,service中可以调用Spring容器中的dao(mapper)。
  3. 第三步:整合controller,Spring管理controller接口,在controller调用service。

2.导入jar包

mybatis-3.x.jar、spring3.x.jar(包含springmvc的jar包)、mybatis与spring的整合jar、数据库驱动包、log4j.jar、jstl.jar。如下:

手把手带你实现Spring、Spring MVC与Mybatis整合工程的搭建_第1张图片

3.工程结构

3.1需要创建的配置文件

  1. applicationContext-dao.xml---配置数据源、SqlSessionFactory、mapper扫描器。
  2. applicationContext-service.xml---配置service接口。
  3. applicationContext-transaction.xml--事务管理。
  4. sprintmvc.xml---springmvc的配置,配置处理器映射器、适配器、视图解析器(这里我们统一采用注解的方式进行开发)。
  5. SqlMapConfig.xml---mybatis的配置文件,配置别名、settings、mapper。

工程目录如下:

手把手带你实现Spring、Spring MVC与Mybatis整合工程的搭建_第2张图片

3.2各个配置文件的内容

applicationContext-dao.xml:


    

    
    

    
    
        
        
        
        
        
    


    
    
        
        
        
        
    
    
        
    
    
        
        
        
        

    
    

applicationContext-service.xml:





    

applicationContext-transaction.xml:配置事务,在配置文件中使用声明式事务配置





        
        
        
            
        

        
        
            
                
                
                
                
                
                
                
            
        

        
        
            
        


sprintmvc.xml:




    
    

    
    
    
    
    

    
    
        
        
    



SqlMapConfig.xml:




    
    
        
        

    


    
    
    
        
    


在web.xml文件中加入对前端控制器的配置:

    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
        
            contextConfigLocation
            
            springmvc.xml
        
    

    
        springmvc
        

        *.action
    

另外还需要添加数据库的配置文件db.properties:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=xiaxunwu1996.

在src下创建各个包:mapper、po、controller、service,在web包下创建页面包jsp,工程目录如下:

手把手带你实现Spring、Spring MVC与Mybatis整合工程的搭建_第3张图片

经过上述步骤,我们便完成了Spring、Spring MVC与Mybatis的整合,是不是很简单?没错就是这么简单。接下来我将通过下篇文章一个案例带你快速入门SSM开发介绍利用Spring、Spring MVC与Mybatis的整合项目进行开发一个案例带你快速学会使用SSM框架开发项目。

4.联系

If you have some questions after you see this article,you can tell your doubts in the comments area or you can find some info by clicking these links.

  • Blog@codingXiaxw's blog

  • Weibo@codingXiaxw

  • Zhihu@codingXiaxw

  • Github@codingXiaxw

你可能感兴趣的:(手把手带你实现Spring、Spring MVC与Mybatis整合工程的搭建)