Spring component-scan 的逻辑 、单例模式下多实例问题、事务失效
2024-08-27 23:04:59
原创内容,转发请保留:http://www.cnblogs.com/iceJava/p/6930118.html,非常欢迎指正,谢谢
之前遇到该问题,今天查看了下 spring 4.x 的代码 一,先理解下 context:component-scan 处理过程:
<!-- scan the package and the sub package -->
<!--
【重要】:容易产生事务失效的地方,见:http://jinnianshilongnian.iteye.com/blog/1762632
处理逻辑(入口见:org.springframework.context.config.ContextNamespaceHandler):
1. context:component-scan 表示是否扫描指定路径下的所有 .class 文件;
参见 org.springframework.core.io.support.PathMatchingResourcePatternResolver.getResources 方法 2. use-default-filters,是否使用将 默认的 AnnotationTypeFilter 增加到 include-filter 过滤器,包括:
@Component(包括子注解@Service、@Reposity、@Controller)、@ManagedBean、@Named注解 的Bean
也就是说,如果使用 use-default-filters = true, 就不需要 <context:annotation-config/> 配置了
参见 org.springframework.context.annotation.ComponentScanBeanDefinitionParser.configureScanner 3. 遍历所有的bean, 保留满足 "不是 exclude-filter 黑名单、并且至少满足一条 include-filter 白名单" .class 文件
参见 org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.isCandidateComponent 方法
16 -->
<context:component-scan base-package="com.hm.mobile" use-default-filters="false" >
<context:include-filter type="regex" expression=".*Controller$" />
<context:include-filter type="regex" expression=".*Interceptor$" />
</context:component-scan>
二:单例模式下的多实例问题
1. 包结构:
MessageController、MessageConsumerListener、MessageProviderService 分别 使用了 @Controller @Service @Service
2. application.xml 配置文件片段
<context:component-scan base-package="com.hm.mobile" >
<context:exclude-filter type="regex" expression=".*Controller$" />
<context:exclude-filter type="regex" expression=".*Interceptor$" />
</context:component-scan>
不难理解,在该配置下,Spring 容器 扫描到:MessageConsumerListener、MessageProviderService 并实例化, 其中 MessageController 被黑名单排除
3. dispatcher-servlet.xml 配置文件片段
<context:component-scan base-package="com.hm.mobile">
<context:include-filter type="regex" expression=".*Controller$" />
<context:include-filter type="regex" expression=".*Interceptor$" />
</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 容器的
备注:第三点,是本人自己的猜想,没来得及去验证。
最新文章
- 使用-MM生成include指令和依赖生成(make include directive and dependency generation with -MM)
- HTML 运算符、类型转换
- Bzoj3893 [Usaco2014 Dec]Cow Jog
- [Unity2D]脚本的使用规则
- JS小练习 留言功能
- Decode放在where条件后的新用法
- linux的HugePage与oracle amm关系
- json 语义分析
- 照片浏览器软件-WTL开发的照片浏览器
- 一位学长的ACM总结(感触颇深)
- JAVA事件监听机制学习
- 通过Servlet实现汉字验证码
- Javascript中的浅拷贝和深拷贝
- 如何在linux下录制terminal操作?
- H5之画布canvas小记,以及通过画布实现原子无规则运动
- 微信小程序开发05-日历组件的实现
- 【Idea】-NO.163.Idea.2 -【How to show the horizontal scroll?】
- java自动化学习笔记
- Structured Streaming Programming Guide结构化流编程指南
- MVC扩展HttpHandler