問題是這樣的,我按照正常的配置文件結構配置,然后每次啟動起來都提示找不到 Controller ,反反復復看配置文件沒發(fā)現(xiàn)問題,依賴也正確,甚至連數(shù)據(jù)庫連接池都換了,也沒解決 Controller Not Found 的問題。。。
后來過了一天我想了一下,既然是找不到 Controller ,那么就是 Controller 的類沒被找到,那么如果沒被找到的話,是不是掃描的時候出了問題呢?
我原來的配置是這樣的
<context:component-scan base-package="cn.lncsa.controller.*"/>
然后我試了一下增加了 Controller 的 filter
<context:component-scan base-package="cn.lncsa.controller.*">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
問題并沒有被解決。
后來觀察,發(fā)現(xiàn) base-package 參數(shù)是 "cn.lncsa.controller.*",然后回頭對比了一下按照教程做的能正常運行的 Helloworld ,是 "net.catten.mvc.*" 而不是"net.catten.mvc.controller.*",我在想是不是這個通配符的問題,于是便試著把 base-package 改成 "cn.lncsa.controller"
<context:component-scan base-package="cn.lncsa.controller"/>
問題解決。。。。
然后在想為什么呢?
是這樣的,base-package 指的是掃描器從那個包開始掃描, "cn.lncsa.controller.*" 指的是掃描 controller 包下面的任何包,也就是說 * 通配符是改變了掃描基于的包了,不再是 controller 而是 controller 里面的各個子包。而我的 Controller 類是放在這個包下的,掃的是根包里的子包的類而不是根包里的類,當然就搜索不到 Controller 了。
那么這個錯誤的配置除了上面這么改還能怎么改呢?
<context:component-scan base-package="cn.lncsa.*">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
這樣改就好了。雖然方法不同但是原理都是更改掃描的根包。第一種方法是直接明確地指出掃描的地方。第二種方法是掃描 cn.lncsa 里面的子包,但是增加 include-filter, 使其只掃描 Controller 類。
當然我的習慣是使用第一種。
還有需要注意的是,因為 SpringMVC 一般是和 Spring 共用, 所以會有重復掃描類的問題。我們的 Controller 是交給 SpringMVC 所屬的容器管理的,所以應該讓主要的 Spring IOC 容器忽略掉這些 Controller。不然會造成重復掃描,生成重復的對象在兩個 IOC 容器里。
所以除了配置 spring-mvc 的 applicationContext 以外,也要在主要的 applicationContxt 里配置掃描器。
<context:component-scan base-package="cn.lncsa">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
增加 exclude-filter 就能讓主要的 IOC 容器忽略掉這些 Controller