1. 程式人生 > >Spring和MyBatis的整合詳解

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

當使用 <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>