Spring和SpringMVC包扫描总结

本文解析了Spring框架如何使用父容器加载除Controller外的Bean,而SpringMVC作为子容器仅加载带有@Controller注解的Bean。通过配置ApplicationContext.xml和SpringMvc-context.xml,实现非控制器Bean和控制器Bean的分别扫描。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原理

Spring使用父容器,SpringMVC使用子容器来加载Bean,父容器内容对子容器可见,子容器内容对父容器不可见,猜测是加载顺序导致;

所以让父容器扫描除controller外Bean,子容器扫描controller类来完成servlet转发;

最后再ApplicationContext.xml和SpringMvc-context.xml看到如下:

<!-- Spring容器中注册非@controller注解的Bean -->
<context:component-scan base-package="com.hafiz.www">
   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- SpringMVC容器中只注册带有@controller注解的Bean -->
<context:component-scan base-package="com.hafiz.www" use-default-filters="false">
   <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>

代码

 

参考资料

https://www.cnblogs.com/junzi2099/p/8042476.html

https://www.cnblogs.com/hafiz/p/5875740.html

红包扫一扫,后续不断努力扒源码,用最简单方式介绍原理
支付红包

努力扒源码,用图、表、简单文字说明原理,我喜欢简单,就把最简单原理传递给你!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值