错误信息:
ERROR[localhost-startStop-1] - Context initialization failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.itheima.core.service.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
提示信息:执行上下文失败,没有相应的bean可以用
分析:bean没有扫描到,此代码的问题则为,在web.xml文件中配置的 application-context.xml 所用的监听器的架包错误
<!-- 配置加载Spring文件的监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
<!-- 引入错误架包 --> org.springframework.web.context.ContextCleanupListener
<!-- 正确架包 --> org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
关于 application-context.xml 和 spring-mvc.xml 配置的理解
1、application-context.xml是全局的,应用于多个serverlet,配合listener一起使用,web.xml中配置如下:
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
2、spring-mvc.xml 是spring mvc的配置,web.xml中配置如下:
<!--配置springmvc DispatcherServlet-->
<!-- 配置Spring MVC 前端核心控制器
-->
<servlet>
<!-- 配置前端过滤器 -->
<servlet-name>crm</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 初始化时加载配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- Spring MVC配置文件的地址 -->
<param-value>classpath:springmvc-config.xml</param-value>
</init-param>
<!-- 表示容器在启动时立即加载Servlet -->
<load-on-startup>1</load-on-startup>
</servlet>