前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >为什么applicationContext.xml和spring-servlet.xml中都有注解过滤<context:component-scan base-package="myproject">

为什么applicationContext.xml和spring-servlet.xml中都有注解过滤<context:component-scan base-package="myproject">

作者头像
yaohong
发布2019-09-11 16:04:30
5250
发布2019-09-11 16:04:30
举报
文章被收录于专栏:姚红专栏姚红专栏

在刚学习SpringMVC框架整合时,你也许会产生疑问为什么Spring.xml和SpringMVC.xml中都有注解过滤。

<context:component-scan base-package="myproject"> 和<context:component-scan base-package="myproject.controller" />

在这里有一个比较有意思的问题,初学者也会产生困惑,那么他究竟有何不同?我思考和查询很久,话不多说,也实践做起:

(1)只在applicationContext.xml中配置如下

<context:component-scan base-package="myproject">

启动不报错,,但@Controller失效

(2)只在spring-servlet.xml中配置上述配置

Error creating bean with name 'org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0' defined in ServletContext resource [/WEB-INF/spring-mvc-......

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'commonController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private eis.service.ICollegeServer eis.controller.CommonController.collService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [eis.service.ICollegeServer] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

(3)在applicationContext.xml和spring-servlet.xml中都配置过滤<context:component-scan base-package="myproject"> 和<context:component-scan base-package="myproject.controller" />,

不报错,请求正常,

总结:由此可以分析<context:component-scan base-package="myproject">主要过滤@Controller,同时还查资料了解<context:component-scan base-package="myproject.controller" /> 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-09-25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档