org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type **

spring 工程运行时报错:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name ***: Unsatisfied dependency expressed through field ***; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type *** available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

先把以下可能的原因都排除了:
1. 没写 @Service 之类的 bean 声明注解,这个 IDE 就会检测出来并提示错误;
2. 没在上下文配置文件中声明 <context:component-scan base-package="" />,这个 IDE 也能检测出来;
3. bean 所在的位置不在 component-scan base-package 下;

最后检查 web.xml 配置文件发现了问题所在:
因为上述 bean 我都是在 额外的上下文配置 中导进来的,如果启用了 额外的上下文配置,类似:

<!-- Extra context configuration -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-*.xml</param-value>
    </context-param>

那么相对应的必须启动 ContextLoaderListener – 上下文装载监听器,也就是要配置:

<!-- Setup ContextLoaderListener.
        Attention: without this, all context cannot be loader in context-param -->
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

否则,你<context-param>在配置的所有上下文都不会被导进来,而且这个 IDE 检测不出来,只会在程序运行的时候才报上述的错误。

原文地址:https://www.cnblogs.com/lvlang/p/10586333.html