struts2+spring+mybatis框架搭建

最近要做一个小项目,本来打算用springmvc+spring+mybatis,因为springmvc刚学项目时间又紧所以采用比较熟悉的struts2替代springmvc。

  • 目录结构
    struts2+spring+mybatis框架搭建_第1张图片
  • 需要引用的JAR包 ,我这里用的是struts2-2.1,spring4.3,mybatis3.3版本

    struts2+spring+mybatis框架搭建_第2张图片
    struts2和spring整合需要一个整合插件包struts2-spring-plugin.jar,这里需要说明一下,我最开始用的是struts2-spring-plugin-2.5.5.jar结果出现错误,引起原因是版本兼容性问题,最好与struts2的版本保持一致。

  • web.xml配置


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>swipedisplay-name>

    
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:spring-beans.xmlparam-value>
    context-param>

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>

    <filter>
        <filter-name>struts2filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
    filter>
    <filter-mapping>
        <filter-name>struts2filter-name>
        <url-pattern>*.actionurl-pattern>
    filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jspwelcome-file>
    welcome-file-list>
web-app>
  • mybatis配置



<configuration>
    <settings>
        
        <setting name="cacheEnabled" value="true" />
        
        <setting name="lazyLoadingEnabled" value="true" />
        
        <setting name="aggressiveLazyLoading" value="false" />
        
        <setting name="mapUnderscoreToCamelCase" value="true" />
    settings>
    <typeAliases>
        
        <package name="com.csyq.model" />
        <package name="com.csyq.vo" />
        
    typeAliases>
    
    
configuration>
  • 数据库
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@200.200.200.16:1521:orcl
#用username跟系统名重名,会引起传入值错误
user=swipe
password=1234

initialSize=0
maxActive=20
maxIdle=10
minIdle=1
maxWait=30000
  • spring整合mybatis及基本配置

<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"
    xmlns:aop="http://www.springframework.org/schema/aop"
    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.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
    
    <context:property-placeholder location="classpath:db.properties"/>
    
    <context:component-scan base-package="com.csyq.action">context:component-scan>
    <context:component-scan base-package="com.csyq.service.impl">context:component-scan>
    
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="maxIdle" value="${maxIdle}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxWait" value="${maxWait}"/>
    bean>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>
    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            
            
            <tx:method name="get*" read-only="true"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="*"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:pointcut expression="execution(* com.csyq.service.*.*(..))" id="txPointCut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
    aop:config>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/csyq/mapper/*.xml">property>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.csyq.mapper">property>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory">property>
    bean>
beans>

这里有一点要注意的是,添加事务切入后,启动tomcat会报以下错误

严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener  
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImp' defined in file [E:\javaee\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\scm1.2\WEB-INF\classes\com\hw\service\Imp\UserServiceImp.class]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0': Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException  
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:452)  
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)  
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)  
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)  

好像是struts与spring有JAR包冲突引起的,需要引入aspectjweaver-1.8.9.jar

  • struts.xml



<struts>
    <constant name="struts.i18n.encoding" value="utf-8">constant>
    
    <constant name="struts.objectFactory" value="spring">constant>

    <package name="user_default" extends="struts-default">
        
        <action name="login" method="login" class="loginAction">
            <result name="success">success.jspresult>
        action>
    package>
struts>
  • Action
    Struts2和Spring整合后, Action实例由spring生成和管理,spring生成对象默认为单例,而Struts2则是每次请求都会生成一个Action,Action是类级别的,参数是成员变量,采用单例模式会引起线程冲突,所以需要将scope改为prototype
@Controller
@Scope("prototype")
public class LoginAction extends BaseAction{

    private UserQueryVo userVo;
    @Autowired
    private UserService userService;
    public String login(){
        return "success";
    }

    public UserQueryVo getUserVo() {
        return userVo;
    }
    public void setUserVo(UserQueryVo userVo) {
        this.userVo = userVo;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
  • Mapper
public interface UserMapper {
    public UserBean getUser(UserQueryVo userVo);
}
  • Mapper.xml



<mapper namespace="com.csyq.mapper.UserMapper">
    <select id="getUser" resultType="userBean" parameterType="userQueryVo">
        select id,name,unitid,mobile from t_user where userid=#{user.userId} and username = #{user.userName}
    select>
mapper>

你可能感兴趣的:(java)