Spring component-scan 的邏輯 、單例模式下多實例問題、事務失效


原創內容,轉發請保留:http://www.cnblogs.com/iceJava/p/6930118.html,非常歡迎指正,謝謝

之前遇到該問題,今天查看了下 spring 4.x 的代碼

一,先理解下 context:component-scan 處理過程:
 1 <!-- scan the package and the sub package -->
 2 <!--
 3        【重要】:容易產生事務失效的地方,見:http://jinnianshilongnian.iteye.com/blog/1762632
 4        處理邏輯(入口見:org.springframework.context.config.ContextNamespaceHandler):
 5        1. context:component-scan 表示是否掃描指定路徑下的所有 .class 文件;
 6            參見 org.springframework.core.io.support.PathMatchingResourcePatternResolver.getResources 方法
 7 
 8        2. use-default-filters,是否使用將 默認的 AnnotationTypeFilter 增加到 include-filter 過濾器,包括:
 9            @Component(包括子注解@Service、@Reposity、@Controller)、@ManagedBean、@Named注解 的Bean
10            也就是說,如果使用 use-default-filters = true, 就不需要 <context:annotation-config/> 配置了
11            參見 org.springframework.context.annotation.ComponentScanBeanDefinitionParser.configureScanner
12 
13 
14        3. 遍歷所有的bean, 保留滿足 "不是 exclude-filter 黑名單、並且至少滿足一條 include-filter 白名單" .class 文件
15            參見 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isCandidateComponent 方法    
16 --> 17 <context:component-scan base-package="com.hm.mobile" use-default-filters="false" > 18 <context:include-filter type="regex" expression=".*Controller$" /> 19 <context:include-filter type="regex" expression=".*Interceptor$" /> 20 </context:component-scan>

 

二:單例模式下的多實例問題

1. 包結構:

  

MessageController、MessageConsumerListener、MessageProviderService 分別 使用了 @Controller @Service @Service

 

2. application.xml 配置文件片段

 

1 <context:component-scan base-package="com.hm.mobile" >
2     <context:exclude-filter type="regex" expression=".*Controller$" />
3     <context:exclude-filter type="regex" expression=".*Interceptor$" />
4 </context:component-scan>

 

  不難理解,在該配置下,Spring 容器 掃描到:MessageConsumerListener、MessageProviderService 並實例化, 其中 MessageController 被黑名單排除

 

3. dispatcher-servlet.xml 配置文件片段

1 <context:component-scan base-package="com.hm.mobile">
2     <context:include-filter type="regex" expression=".*Controller$" />
3     <context:include-filter type="regex" expression=".*Interceptor$" />
4 </context:component-scan>

  Spring MVC 容器 掃描到了 MessageConsumerListener、MessageProviderService、MessageController 並實例化 

 

4. 通過 vituralVM,我們得到了證實:

 

5. 在 application-servlet.xml 增加  use-default-filters="false"  之后

 

 
        

三:事務失效問題

  a. 一般情況下,我們都是在 Spring 配置中事務,因此只有 spring 容器中的 service 對象 被 AOP 注入事務;換句話說, Spring MVC 容器中的service對象 是沒有進行 AOP 事務注入的

     b. 因為 Spring mvc 中注入的 service 對象是 自身容器中的 對象,而不是 Spring 容器的

     備注:第三點,是本人自己的猜想,沒來得及去驗證。

 


免責聲明!

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



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