Spring MVC @Transactional注解方式事务失效的解决办法

Spring配置文件 applicationContext.xml

<context:component-scan base-package="com.xdxx.ssm">
        <!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> -->
    </context:component-scan>

Spring mvc配置文件.dispatcher.xml

<context:component-scan base-package="com.xdxx.ssm">
        <!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />  -->  
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> 
    </context:component-scan>

web.xml

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

    <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/ApplicationContext-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

  java的service代码:

  @Transactional
    @Override
    public Map<String, Object> pubNotice(NoticeForm form,HttpSession session) throws Exception {


}

失效原因:

Spring容器优先加载由ServletContextListener(对应ApplicationContext.xml)产生的父容器,

而SpringMVC(对应ApplicationContext-mvc.xml)产生的是子容器。

子容器Controller进行扫描装配时装配的@Service注解的实例是没有经过事务加强处理,

即没有事务处理能力的Service,而父容器进行初始化的Service是保证事务的增强处理能力的。

如果不在子容器中将Service exclude掉,此时得到的将是原样的无事务处理能力的Service,

因为在多上下文的情况下,如果同一个bean被定义两次,后面一个优先。

所以上面配置文件中去掉注释部分就是优化后的最终配置.

原文地址:https://www.cnblogs.com/guoyansi19900907/p/6439681.html