在剛學習SpringMVC框架整合時,你也許會產生疑問為什麼Spring.xml和SpringMVC.xml中都有註解過濾。 <context:component-scan base-package="myproject"> 和<context:component-scan base-package ...
在剛學習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 定義的功能,同時還啟用了註釋驅動自動註入的功能。