spring專案啟動伺服器找不到bean的解決問題
今天在配置springMVC專案框架,啟動tomcat,然後我的一個物件注入失敗,找不到bean,如下:
Error creating bean with name 'userController': Injection of resource dependenci.......
解決辦法如下:
這種問題我遇到2次:
1、提示我搭建專案使用的是原生dao層,結果是SQL檔案裡面namespace的地址錯誤
修改地址之後就可以了。
2、這種就比較難找了,具體不說了,直接上方案:
原來是我的web.xml檔案少寫了這個監聽器
加上去就可以了。
org.springframework.web.context.ContextLoaderListener的作用:
ContextLoaderListener這個監聽器繼承自ContextLoader並且實現了ServletContextListener,他的主要作用是去尋找並讀取spring主配置檔案ApplicationContext.xml(也就是context-param中所定義的contextConfigLocation),然後啟動WebApplicationContext,也可叫做web應用上下文,並且最重要的是,它將WebApplicationContext注入到servletContext容器中(作為servletContext的一個attribute,屬性),並且在WebApplicationContext中保留了一個servletContext的引用。
所以我們可以通過WebApplicationContext得到servletContext,也可以通過servletContext獲取到WebApplicationContext。
通過WebApplicationContext得到servletContext:
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
ServletContext servletContext = webApplicationContext.getServletContext();
通過servletContext獲取WebApplicationContext:
ServletContext servletContext = event.getServletContext();
ApplicationContext application = WebApplicationContextUtils .getWebApplicationContext(servletContext);
後記:專案配置很多坑,不小心掉進去很難找到問題。所以以後寫配置一定要仔細。。