NoSuchBeanDefinitionException: No bean named 'xxx' is defined

一開始學習spring這種問題恐怕十分常見了,遇見這樣的問題基本就是以下幾種情況

1. 缺少包或者包衝突

我把我用到的包貼出來大家可以對照一下

//spring基本依賴
compile "org.springframework:spring-context:4.3.9.RELEASE"
compile "org.springframework:spring-beans:4.3.9.RELEASE"
compile "org.springframework:spring-core:4.3.9.RELEASE"
compile "org.springframework:spring-expression:4.3.9.RELEASE"
//spring的aop操作依賴
compile "org.springframework:spring-aspects:4.3.9.RELEASE"
compile "org.springframework:spring-aop:4.3.9.RELEASE"
compile "aspectj:aspectjweaver:1.5.4"
compile "aopalliance:aopalliance:1.0"
//spring的jdbc操作依賴
compile "mysql:mysql-connector-java:5.1.38"
compile "org.springframework:spring-jdbc:4.3.9.RELEASE"
compile "org.springframework:spring-tx:4.3.9.RELEASE"
compile "com.mchange:c3p0:0.9.5.2"
//springMVC的依賴
compile "org.springframework:spring-webmvc:4.3.9.RELEASE"
compile "org.springframework:spring-web:4.3.9.RELEASE"
compile "javax.servlet:jstl:1.2"
compile "javax.servlet:servlet-api:2.5"
compile "javax.servlet.jsp:jsp-api:2.2"

2. bean是否未定義或名字寫錯

仔細檢查自己的bean的名字有沒有寫錯,如果用@Autowired的話,還要檢查類型是否匹配。

還要檢查@Repository等有沒有忘了配置

3. spring的配置xml的路徑是否正確

在resource下需要用classpath:開頭(如果不行可以試試classpath*:),在webapp下需要WEB_INF/xxx

還要注意,你的路徑應該對應的是tomcat下的路徑!

4. web.xml配置問題(這也是我這次出的問題)

如果你用單元測試(junit)可以通過,但是開了tomcat就報錯的話,基本都是web.xml配置問題

我當時已經把spring的xml配置進去了,也就是這樣,但還是報錯

<context-param>
        <!--名字必須是這個,路徑要仔細檢查有沒有錯-->
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext.xml,classpath:spring/spring_mybatis.xml</param-value>
    </context-param>

最後才發現我的監聽器沒有加

<!--spring監聽器,加載spring文件-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

順帶提一下,前端控制器的init-param最好要配一下,不然他會自動尋找xxx-servlet.xml加載,這裏也有可能出錯

 <!--springmvc前段控制器配置-->
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--配置springmvc加載的配置文件(處理器、映射器、適配器等)-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>

5. 天下之大無奇不有,如果還有其他奇葩的錯的,還恕我無能爲力了

聽說各個版本還會有一些不同的問題,這些就很難辦了(主要是路徑的問題,可以試試多用上點*,碰上的機率會大一點…)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章