Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

jopen 10年前發布 | 380K 次閱讀 JEE框架 Spring MVC

一、安裝java環境(略)

    這方面資料很多

    我的環境是JDK6+eclipse4 j2ee版,自帶Maven等一些插件

二、安裝Maven(略)

    Maven安裝簡單裝好后修改 根目錄/conf/settings.xml,配置好maven庫目錄

    Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

    打開eclipse windows-preference-maven-userSettings-global settings選擇maven安裝目錄的settings.xml文件

    點擊maven在主配置上勾選,這時maven會下載index可能會很慢。需要等等

    Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

三、創建maven工程

    點擊Eclipse菜單欄File->New->Ohter->Maven->選擇項目目錄->next->選擇項目類型

    Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

    搜索web,創建項目->next

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

填寫groupId和artifact Id->finish

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

項目配置

右擊項目-new

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

創建如下幾個文件

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

配置build path

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

分別修改輸出路徑為

src/main/resources        對應        target/classes

src/main/java        對應        target/classes

src/test/resources        對應        target/test-classes

src/test/java        對應        target/test-classes

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

設置JDK版本

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

設置部署程序集(Web Deployment Assembly)

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4    

把兩個test目錄去掉!!!

到此項目算是部署完成了。如果有其他問題百度一下吧!!

三 spring mvc+spring+mybatis配置

首先pom.xml文件內容

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.xxl.maven_web</groupId>
  <artifactId>xxl_maven_web</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>xxl_maven_web Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <build>
    <finalName>xxl_maven_web</finalName>
  </build>
  <dependencies>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-web</artifactId>
          <version>4.0.6.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>4.11</version>
          <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>servlet-api</artifactId>
          <version>2.5</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-aspects</artifactId>
          <version>4.0.6.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-webmvc</artifactId>
          <version>4.0.6.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context-support</artifactId>
          <version>4.0.6.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.freemarker</groupId>
          <artifactId>freemarker</artifactId>
          <version>2.3.20</version>
      </dependency>
      <dependency>
          <groupId>commons-logging</groupId>
          <artifactId>commons-logging</artifactId>
          <version>1.2</version>
      </dependency>
      <dependency>
          <groupId>commons-lang</groupId>
          <artifactId>commons-lang</artifactId>
          <version>2.6</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-mock</artifactId>
          <version>2.0.8</version>
          <scope>test</scope>
      </dependency>
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.14</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.2.7</version>
      </dependency>
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.2.2</version>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.32</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-tx</artifactId>
          <version>4.0.6.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-jdbc</artifactId>
          <version>4.0.6.RELEASE</version>
      </dependency>
      <dependency>
          <groupId>org.apache.commons</groupId>
          <artifactId>commons-collections4</artifactId>
          <version>4.0</version>
      </dependency>
      <dependency>
          <groupId>commons-dbcp</groupId>
          <artifactId>commons-dbcp</artifactId>
          <version>1.4</version>
      </dependency>
      <dependency>
          <groupId>commons-pool</groupId>
          <artifactId>commons-pool</artifactId>
          <version>1.6</version>
      </dependency>
      <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-test</artifactId>
          <version>4.0.6.RELEASE</version>
          <scope>test</scope>
      </dependency>
  </dependencies>
</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
                             http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
         version="2.5" >

    <!-- 區分項目名稱,防止默認重名 -->
    <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>maven.xxl_web.root</param-value>
    </context-param>

    <!-- Spring的log4j監聽器 -->
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!-- 字符集 過濾器  -->
    <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- 設置Spring容器加載配置文件路徑 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext-*.xml</param-value>
    </context-param>

    <!-- Spring view分發器 -->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
        <!--攔截/*,這是一個錯誤的方式,請求可以走到Action中,但轉到jsp時再次被攔截,不能訪問到jsp。 
            攔截/,restful風格 弊端:會導致靜態文件(jpg,js,css)被攔截后不能正常顯示。解決辦法看dispatcher-->
    </servlet-mapping>

    <!-- Spring會創建一個WebApplicationContext上下文,稱為父上下文(父容器) ,保存在 ServletContext中,key是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的值。
    可以使用Spring提供的工具類取出上下文對象:WebApplicationContextUtils.getWebApplicationContext(ServletContext);
     
    DispatcherServlet是一個Servlet,可以同時配置多個,每個 DispatcherServlet有一個自己的上下文對象(WebApplicationContext),稱為子上下文(子容器),子上下文可以訪問父上下文中的內容,
    但父上下文不能訪問子上下文中的內容。 它也保存在 ServletContext中,key是"org.springframework.web.servlet.FrameworkServlet.CONTEXT"+Servlet名稱。當一個Request對象產生時,
    會把這個子上下文對象(WebApplicationContext)保存在Request對象中,key是DispatcherServlet.class.getName() + ".CONTEXT"。
    可以使用工具類取出上下文對象:RequestContextUtils.getWebApplicationContext(request);-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>  


    <welcome-file-list>
        <welcome-file>/login.jsp</welcome-file>
    </welcome-file-list>

</web-app>

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:aop="http://www.springframework.org/schema/aop" 
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd 
        http://www.springframework.org/schema/mvc 
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- <mvc:annotation-driven /> -->
    <!--注解說明  
    <context:annotation-config />--> 
    
   <!--  @Controller 聲明Action組件
    @Service    聲明Service組件    @Service("myMovieLister") 
    @Repository 聲明Dao組件
    @Component   泛指組件, 當不好歸類時. 
    @RequestMapping("/menu")  請求映射
    @Resource  用于注入,( j2ee提供的 ) 默認按名稱裝配,@Resource(name="beanName") 
    @Autowired 用于注入,(spring提供的) 默認按類型裝配 
    @Transactional( rollbackFor={Exception.class}) 事務管理
    @ResponseBody
    @Scope("prototype")   設定bean的作用域 -->
    <context:component-scan base-package="com.xxl.app.**.control" />

    <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>
    <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>
    <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>

    <bean name="handlerAdapter" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" >
        <!--<property name="messageConverters">
            <list>
                 <ref bean="byteArray_hmc" />
                <ref bean="string_hmc" /> 
            </list>
        </property>-->
    </bean>
    <!-- <bean id="byteArray_hmc" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />處理..
    <bean id="string_hmc" class="org.springframework.http.converter.StringHttpMessageConverter" />處理..  -->
    <bean name="handlerMapping" class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
        <!-- 只會攔截@RequestMapping的URL
        <property name="interceptors">
             <list>
                 <bean class="com.mvc.MyInteceptor"></bean>
             </list>
         </property> -->
    </bean>   
    <!-- freemarker的配置 -->  
    <bean id="freemarkerConfigurer" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="/WEB-INF/view/" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="freemarkerSettings">
            <props>
                <prop key="template_update_delay">10</prop>
                <prop key="locale">zh_CN</prop>
                <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                <prop key="date_format">yyyy-MM-dd</prop>
                <prop key="number_format">#.##</prop>
            </props>
        </property>
    </bean>
    <!-- FreeMarker視圖解析 如返回userinfo。。在這里配置后綴名ftl和視圖解析器。。 -->  
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">  
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />  
        <property name="suffix" value=".html" />  
        <property name="contentType" value="text/html;charset=UTF-8" />
        <property name="exposeRequestAttributes" value="true" />
        <property name="exposeSessionAttributes" value="true" />
        <property name="exposeSpringMacroHelpers" value="true" />
    </bean>
    
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"
        p:basename="i18n/messages" />

<!--    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
    </bean> -->

    <!-- 全局攔截器   會攔截靜態資源
    Spring為我們提供了:
    org.springframework.web.servlet.HandlerInterceptor接口,
    org.springframework.web.servlet.handler.HandlerInterceptorAdapter適配器,
    實現這個接口或繼承此類,可以非常方便的實現自己的攔截器。
     
    有以下三個方法:
     
    Action之前執行:
     public boolean preHandle(HttpServletRequest request,
       HttpServletResponse response, Object handler);
     
    生成視圖之前執行
     public void postHandle(HttpServletRequest request,
       HttpServletResponse response, Object handler,
       ModelAndView modelAndView);
     
    最后執行,可用于釋放資源
     public void afterCompletion(HttpServletRequest request,
       HttpServletResponse response, Object handler, Exception ex)
    <mvc:interceptors >  
     <mvc:interceptor>  
            <mvc:mapping path="/user/*" />  /user/*    
            <bean class="com.mvc.MyInteceptor"></bean>  
        </mvc:interceptor>  
    </mvc:interceptors>  
    -->

    <!-- 總錯誤處理
    這里主要的類是SimpleMappingExceptionResolver類,和他的父類AbstractHandlerExceptionResolver類。
    具體可以配置哪些屬性,我是通過查看源碼知道的。
    你也可以實現HandlerExceptionResolver接口,寫一個自己的異常處理程序。
    <bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView">
           <value>/error/error</value> error頁面可以通過Exception e = (Exception)request.getAttribute("exception")獲得異常信息
        </property>
        <property name="defaultStatusCode">
           <value>500</value>
        </property>
        <property name="warnLogCategory">
           <value>org.springframework.web.servlet.handler.SimpleMappingExceptionResolver</value>
        </property>
    </bean>-->

    <!-- 對靜態資源文件的訪問  方案一 (二選一)
    會把"/**" url,注冊到SimpleUrlHandlerMapping的urlMap中,把對靜態資源的訪問由HandlerMapping轉到
    org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler處理并返回.
    DefaultServletHttpRequestHandler使用就是各個Servlet容器自己的默認Servlet.
    <mvc:default-servlet-handler/> -->

    <!-- 對靜態資源文件的訪問  方案二 (二選一)/images/**映射到ResourceHttpRequestHandler進行處理,
    location指定靜態資源的位置.可以是web application根目錄下、jar包里面,這樣可以把靜態資源壓縮到jar包中。
    cache-period 可以使得靜態資源進行web cache 
    <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>
    <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>
    <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>-->

</beans>

Maven3.0+Spring MVC4+Spring 4+Mybatis3+junit4

applicationContext-bean.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:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:component-scan base-package="com.xxl.app.**.service" />

    <!-- 用于持有ApplicationContext,可以使用SpringContextHolder.getBean('xxxx')的靜態方法得到spring bean對象 -->
    <bean class="com.xxl.app.base.SpringContextHolder" lazy-init="false" />

    <!-- 使用annotation注解方式配置事務 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
    <!-- 使用JDBC事務 -->  
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 引入配置文件 -->
    <context:property-placeholder location="classpath:ini.properties"/>
    
    <!--創建jdbc數據源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
      <property name="driverClassName" value="${driver}"/>
      <property name="url" value="${url}"/>
      <property name="username" value="${username}"/>
      <property name="password" value="${password}"/>
      <property name="maxActive" value="${maxActive}"/>
      <property name="maxIdle" value="${maxIdle}"/>
      <property name="minIdle" value="${minIdle}"/>
    </bean>
    
    <!-- 配置SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <!-- <property name="mapperLocations">
            <list>
                表示在包或以下所有目錄中,以-mapper.xml結尾所有文件
                <value>classpath:config/**/*-mapper.xml</value>
            </list>
        </property> -->
    </bean>

    <!-- 配置mybatis dao注冊,所有dao都繼承sqlMapper
    annotationClass:當指定了annotationClass的時候,MapperScannerConfigurer將只注冊使用了annotationClass注解標記的接口。
    markerInterface:markerInterface是用于指定一個接口的,當指定了markerInterface之后,MapperScannerConfigurer將只注冊繼承自markerInterface的接口。
          如果上述兩個屬性都指定了的話,那么MapperScannerConfigurer將取它們的并集,而不是交集。即使用了annotationClass進行標記或者繼承自markerInterface
          的接口都將被注冊為一個MapperFactoryBean。 
          除了用于縮小注冊Mapper接口范圍的屬性之外,我們還可以指定一些其他屬性,如:
    sqlSessionFactory:這個屬性已經廢棄。當我們使用了多個數據源的時候我們就需要通過sqlSessionFactory來指定在注冊MapperFactoryBean的時候需要使用的SqlSessionFactory,
        因為在沒有指定sqlSessionFactory的時候,會以Autowired的方式自動注入一個。換言之當我們只使用一個數據源的時候,即只定義了一個SqlSessionFactory的時候我們就可以不給
        MapperScannerConfigurer指定SqlSessionFactory。
    sqlSessionFactoryBeanName:它的功能跟sqlSessionFactory是一樣的,只是它指定的是定義好的SqlSessionFactory對應的bean名稱。
    sqlSessionTemplate:這個屬性已經廢棄。它的功能也是相當于sqlSessionFactory的,因為就像前面說的那樣,MapperFactoryBean最終還是使用的SqlSession的getMapper
    方法取的對應的Mapper對象。當定義有多個SqlSessionTemplate的時候才需要指定它。對于一個MapperFactoryBean來說SqlSessionFactory和SqlSessionTemplate只需要其中一個就可以了,
    當兩者都指定了的時候,SqlSessionFactory會被忽略。
    sqlSessionTemplateBeanName:指定需要使用的sqlSessionTemplate對應的bean名稱。-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xxl.app.**.dao"/>
        <property name="markerInterface" value="com.xxl.app.base.dao.SqlMapper"/>
    </bean>


</beans>

mybaitis.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 在這個文件放置一些全局性的配置
    <typeAliases>
        <typeAlias type="com.*.*.bean.*" alias="*"/>
    </typeAliases> -->
</configuration>

單元測試代碼

package xxl.test.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.xxl.app.base.service.IIndexService;

@ContextConfiguration(locations={"classpath:applicationContext-bean.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
//如果是true不會改變數據庫數據,如果是false會改變數據
@TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
public class IndexService {

    @Autowired
    private IIndexService indexService;

    @Test
    public void TestIndex(){

        indexService.doIndex();
    }

}

 

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!