Spring和MyBatis的整合详解

需要哪些配置文件? (3个配置文件)
 
 web.xml,springmvc的配置文件(例子为spring-servlet.xml),spring和mybatis整合的配置文件(applicationContext.xml)

1、web.xml

===============================================================================  
  第一步加载listener:spring的配置(加载spring的相关配置),其实就是spring和mybatis整合的配置文件
=============================================================================== 

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener> 

=============================================================================== 
  第二步:指定spring配置文件的位置和名字。 用于管理spring配置文件,百度contextConfigLocation
=============================================================================== 

默认方式:指定在src目录spring包下面存在applicationContext.xml文件,classpath为src目录

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml</param-value>
    </context-param> 

非默认方式:可以指定文件位置,在WEB-INF目录下有applicationContext.xml文件,一般使用这种。

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param> 

=============================================================================== 
  第三步:配置spring MVC
=============================================================================== 

默认的方式:在web.xml中配置springmvc的servlet的名字xxx,默认的springmvc配置文件名为xx-servlet.xml

这里由于设置名称为spring,所有正确的写法为spring-servlet.xml

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>   
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

非默认的方式:直接在web.xml中配置springmvc的servlet的时候,指定springmvc配置文件的位置和名字。
<!-- Spring MVC servlet -->
  <servlet>
    <servlet-name>SpringMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>
    <!-- 那些url会走SpringMVC -->
  <servlet-mapping>
    <servlet-name>SpringMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

2、spring-servlet.xml

a)引入相关的命名空间mvc和context

xmlns:mvc="http://www.springframework.org/schema/mvc"  

http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd


xmlns:context="http://www.springframework.org/schema/context"  

    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-4.1.xsd 

b)设置注解驱动

<mvc:annotation-driven/>

c)设置controller扫描路径的包名,spring mvc会自动的实例化该包下的controller。
  controller相当于struts中的action,用于处理数据,完成转发。

<context:component-scan base-package="controller"/>

springmvc可以采用xml配置或者注解配置,xml配置很少用,也比较麻烦,我们只讲解注解配置。

3、applicationContext.xml

(1)这两个配置项不再需要:<aop:aspectj-autoproxy/>  <context:annotation-config/>

参考文章

http://my.oschina.net/sherwayne/blog/26261
http://chenjumin.iteye.com/blog/456351

http://blog.sina.com.cn/s/blog_872758480100wtfh.html

当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了

(2)配置datasource (dbcp 需要引入jar包)

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
    <!-- 初始化连接数量; -->
    <property name="initialSize" value="0" />
    <!-- 最大并发连接数     -->
    <property name="maxActive" value="20" />

    <!-- 最大空闲连接数 -->
    <property name="maxIdle" value="20" />
    <!-- 最小空闲连接数 -->
    <property name="minIdle" value="0" />
    <!-- 最大等待时长 -->
    <property name="maxWait" value="60000" />
    <!-- 超过时间限制是否回收 -->
    <property name="removeAbandoned" value="true" />
    <!-- 超过时间限制多长; -->
    <property name="removeAbandonedTimeout" value="180"/>          
    <!-- 数据源连接参数配置; -->
    <property name="username" value="${db.username}"/>
    <property name="url" value="${db.url}"/>
    <property name="password" value="${db.password}"/>
    <property name="driverClassName" value="${db.driver}"/>
</bean>     

(3)配置sessionfactory,并且指明mapper映射文件所在的包名。

  id是固定的

    <!-- 配置SessionFactory -->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="dataSource"/>    
<!-- <property name="mapperLocations" value="classpath:mapper/*.xml" /> -->
    <property name="mapperLocations">
        <list>            
            <value>classpath:mapper/*.xml</value>
        </list>
    </property>
</bean>       

(4)指明mapper接口所在的包名

<!-- 自动扫描mapper接口,注入sqlSessionFactory -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="mapper"/>
</bean>

(5)配置事务管理器,注意:注入的是datasource属性

 <!-- 配置事务管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource" ref="dataSource"/>
  </bean> 

<!-- <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/> -->
  <!-- 定义切面 -->
<aop:config>
    <aop:pointcut expression="execution(* dao.*.* (..))" id="txPointCut"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
  
<!-- 声明式事务 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">            
    <tx:attributes>
         <tx:method name="isValid" propagation="REQUIRED" read-only="true"/>
         <tx:method name="add" propagation="REQUIRED" read-only="true"/>
    </tx:attributes>        
</tx:advice>

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: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.xsd
        http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-4.1.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
		http://www.springframework.org/schema/tx
  		http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
		">    
	<!-- 扫描dao包,当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了 -->   	
	<context:component-scan base-package="dao"/> 
	
	<!-- classpath:代表在src目录下读取db.properties文件,获取数据源参数,property-placeholder占位符$ -->
	<context:property-placeholder location="classpath:db.properties"/>  
	<!-- 配置数据源,dbcp需要引入相关jar包 -->
   <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
	    <!-- 初始化连接数量; -->
	    <property name="initialSize" value="0" />
	    <!-- 最大并发连接数 	-->
	    <property name="maxActive" value="20" />	
	    <!-- 最大空闲连接数 -->
	    <property name="maxIdle" value="20" />
	    <!-- 最小空闲连接数 -->
	    <property name="minIdle" value="0" />
	    <!-- 最大等待时长 -->
	    <property name="maxWait" value="60000" />
	    <!-- 超过时间限制是否回收 -->
	    <property name="removeAbandoned" value="true" />
	    <!-- 超过时间限制多长; -->
	    <property name="removeAbandonedTimeout" value="180"/>          
	    <!-- 数据源连接参数配置; -->
	    <property name="username" value="${db.username}"/>
	    <property name="url" value="${db.url}"/>
	    <property name="password" value="${db.password}"/>
	    <property name="driverClassName" value="${db.driver}"/>
</bean> 	
    <!-- 配置SessionFactory 并且指明mapper映射文件所在的包名,需要引入Mybatis和spring整合的jar包,
    	id这里sqlSessionFactory是固定的不能随便取,因为自动扫描mapper接口包里面用到-->
     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     		<!--dataSource要和配置数据源中bean中的id="dataSource"对应上 -->
	      	<property name="dataSource" ref="dataSource"/>    
			<!-- <property name="mapperLocations" value="classpath:mapper/*.xml" /> -->
			<property name="mapperLocations">
			<list>	
				<!-- 指明映射文件目录位置,这里是在src目录config包下面 -->		
				<value>classpath:config/*.xml</value>
			</list>
			</property>
	</bean>	   
   	<!-- 自动扫描mapper接口包,注入sqlSessionFactory -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="mapper"/>
	</bean>
	 <!-- 配置事务管理器 -->
	  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	      <property name="dataSource" ref="dataSource"/>
	  </bean> 	
	<!-- <tx:annotation-driven transaction-manager="transactionManager"  proxy-target-class="true"/> -->
	  <!-- 定义切面  dao下面的所有类、所有方法都会被事务管理-->
	<aop:config>
	    <aop:pointcut expression="execution(* dao.*.* (..))" id="txPointCut"/>
	    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
	</aop:config>	  
	<!-- 声明式事务 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">            
	    <tx:attributes>
	         <tx:method name="isValid" propagation="REQUIRED" read-only="true"/>
	         <tx:method name="add" propagation="REQUIRED" read-only="true"/>
	    </tx:attributes>        
	</tx:advice>
</beans>

web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">


  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener> 

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param> 
    
    <servlet>
	    <servlet-name>spring</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    
	<servlet-mapping>
	    <servlet-name>spring</servlet-name>
	    <url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

spring-servlet.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:mvc="http://www.springframework.org/schema/mvc" 
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc  
    	http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
        http://www.springframework.org/schema/context  
    	http://www.springframework.org/schema/context/spring-context-4.1.xsd ">
	<!-- 注解驱动 -->
	<mvc:annotation-driven/>
	<!-- 设置controller扫描路径的包名,spring mvc会自动的实例化该包下的controller。
      controller相当于struts中的action,用于处理数据,完成转发。 -->
	<context:component-scan base-package="controller"></context:component-scan>
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
	<property name="prefix" value= ""/>
	<property name="suffix" value= ".jsp"/>
    </bean>    
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                <property name="supportedMediaTypes">  
                    <list>  
                        <value>text/html; charset=UTF-8</value>  
                        <value>application/json;charset=UTF-8</value>  
                    </list>  
                </property>  
     </bean>  
</beans>

猜你喜欢

转载自blog.csdn.net/tangbin0505/article/details/82724141
今日推荐