Spring和SpringMVC掃描注解類沖突
最正確的配置方式
在主容器中applicationContext.xml中,將Controller的注解排除掉
<context:component-scan base-package="com"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
而在springmvc.xml中,將Service注解給去掉
<context:component-scan base-package="com"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" /> </context:component-scan>
因為spring的context是父子容器,所以會產(chǎn)生沖突,由ServletContextListener產(chǎn)生的是父容器,springMVC產(chǎn)生的是子容器,子容器Controller進(jìn)行掃描裝配時裝配了@Service注解的實例,而該實例理應(yīng)由父容器進(jìn)行初始化以保證事務(wù)的增強(qiáng)處理,所以此時得到的將是原樣的Service(沒有經(jīng)過事務(wù)加強(qiáng)處理,故而沒有事務(wù)處理能力。
還有一種方式是將service層改用xml配置,其實這樣做也是變相的讓springmvc無法掃描service,而只能依賴父窗口也就是ServletContextListener來進(jìn)行初始化,這樣同樣被賦予了事務(wù)性。
也可以用直接掃描的方式
直接掃描比較省事,但是事務(wù)回得不到處理,所以在具體的層面上還需要加入注解去聲明事務(wù),比如在dao層和service層加入@Transactional
幾種不同配置的測試
(1)只在applicationContext.xml中配置如下
<context:component-scan base-package="com" />
啟動正常,但是任何請求都不會被攔截,簡而言之就是@Controller失效,出現(xiàn)404錯誤
(2)只在springmvc.xml中配置
<context:component-scan base-package="com" />
啟動正常,請求也正常,但是事物失效,也就是不能進(jìn)行回滾
(3)在applicationContext.xml和springmvc.xml中都配置
<context:component-scan base-package="com" />
啟動正常,請求正常,也是事物失效,不能進(jìn)行回滾
(4)在applicationContext.xml中配置如下
<context:component-scan base-package="com.service" />
在springmvc.xml中配置如下
<context:component-scan base-package="com.action" />
或者按最正確的配置applicationContext.xml,將Controller的注解排除掉 ,springmvc.xml,將Service注解給去掉
此時啟動正常,請求正常,事物也正常了。
Spring和SpringMVC注解掃描注意事項
現(xiàn)象
Springmvc和Spring設(shè)置自動掃描文件夾自動注入bean的時候有時候出現(xiàn)沖突
方法
1:springmvc設(shè)置只掃描controller
2:spring設(shè)置不掃描controller
代碼:
springmvc 的掃描設(shè)置只掃描controller spring的掃描設(shè)置為不掃描controller的 防止重復(fù)注入bean管理 (出現(xiàn)未錯誤) <!-- 設(shè)置使用Spring注解的類所在的jar包 設(shè)置不掃描下面規(guī)則的 --> <context:component-scan base-package="com.oig"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan> <!-- 設(shè)置使用SpringMvc注解的類所在的jar包 設(shè)置只掃描自定義規(guī)則的--> <context:component-scan base-package="com.oig" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice" /> </context:component-scan>
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/xiaobao5214/article/details/52042041