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被定義兩次,后面一個優先。

所以上面配置文件中去掉注釋部分就是優化后的最終配置.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM