Как настроить spring-servlet.xml для исправления ошибки Injection в проекте Spring-MVC 3.0? - PullRequest
0 голосов
/ 03 июля 2018

Я работаю над проектом Spring MVC 3.0 и только что использовал @Autowired в своем коде, но я получил следующее сообщение об ошибке в окне консоли:

严重: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.maskkk.service.UserService com.maskkk.controller.LoginController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.maskkk.service.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1146)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:599)
    at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
    at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:518)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:459)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    at javax.servlet.GenericServlet.init(GenericServlet.java:158)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1151)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1038)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5027)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5337)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1407)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1397)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

logincontroller - проверять людей, которые заходят на сайт. Ниже приведен его код:

package com.maskkk.controller;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;

import com.maskkk.model.Login;

import com.maskkk.model.User;

import com.maskkk.service.UserService;

@Controller

public class LoginController {

 @Autowired

UserService userService;

@RequestMapping(value = "/login", method = RequestMethod.GET)

 public ModelAndView showLogin(HttpServletRequest request, 
 HttpServletResponse response) {

ModelAndView mav = new ModelAndView("login");

mav.addObject("login", new Login());

return mav;

}

@RequestMapping(value = "/loginProcess", method = RequestMethod.POST)

public ModelAndView loginProcess(HttpServletRequest request, 
HttpServletResponse response,
@ModelAttribute("login") Login login) {

 ModelAndView mav = null;

 User user = userService.validateUser(login);

 if (null != user) {

 mav = new ModelAndView("welcome");

 mav.addObject("firstname", user.getFirstname());

 } else {

 mav = new ModelAndView("login");

 mav.addObject("message", "Username or Password is wrong!!");

 }

 return mav;

 }

 }

С:

@Autowired

UserService userService;

Сервис пользователя ниже:

package com.maskkk.service;

import com.maskkk.model.Login;
import com.maskkk.model.User;

public interface UserService {

   void register(User user);

   User validateUser(Login login);
}

Структура моего проекта похожа на приведенную выше: enter image description here

А мой spring-servlet.xml ниже:

<beans xmlns="http://www.springframework.org/schema/beans"  
xmlns:context="http://www.springframework.org/schema/context"  
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
xsi:schemaLocation="  
    http://www.springframework.org/schema/beans       
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context   
    http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">  

 <!-- 下面是配置扫描包的位置,包名为com.maskkk,也就是说,我们的试图解析器应该放在 
 com.maskkk包下. -->
 <!-- import resource="classpath:com/config/user-beans.xml" /> -->

 <context:component-scan base-package="com.maskkk.*" />
 <context:annotation-config />
 <!-- <context:component-scan base-package="com.maskkk.*" />  --> 
 <!-- 自动扫描(自动注入) -->
 <!-- <context:component-scan base- 
 package="com.maskkk.controller.LoginController" />
 <context:component-scan base-package="com.maskkk.service.UserService" /> -->

 <mvc:resources mapping="/image/**" location="/image/" />
 <bean class="org.springframework.web.servlet.mvc.annotation
 .AnnotationMethodHandlerAdapter" />
 <bean class="org.springframework.web.servlet.mvc.annotation
 .DefaultAnnotationHandlerMapping" />
 <bean id="viewResolver"  
 class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <!-- 前缀,我们的视图文件应该放到/WEB-INF/view/目录下,这里我们需要在WEB-INF下面 
  创建view文件夹 -->  
  <property name="prefix" value="/" />  
  <!-- 设置后缀为.jsp -->
   <property name="suffix" value=".jsp" />  
  </bean>




   <bean id="messageSource" 
   class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages" />
   </bean>

   <bean id="multipartResolver"class="org.springframework.web
   .multipart.commons.CommonsMultipartResolver">  
   <property name="maxUploadSize" value="209715200" />     
   <property name="defaultEncoding" value="UTF-8" />  
   <property name="resolveLazily" value="true" />  
    </bean>  
   <bean class="org.springframework.beans.factory
  .annotation.AutowiredAnnotationBeanPostProcessor"/>
  <bean  class="org.springframework.web.servlet.mvc
  .method.annotation.RequestMappingHandlerMapping">  
  </bean>  
  <bean class="org.springframework.web.servlet.mvc
  .method.annotation.RequestMappingHandlerAdapter">  
   <property name="messageConverters">  
    <list>  
        <bean class="org.springframework.http.converter.json
        .MappingJackson2HttpMessageConverter" />  
    </list>  
    </property>  
    </bean> 
    <!-- 加入json支持 -->  
    <mvc:annotation-driven />
     <!-- 处理请求response返回值,如下配置能正确返回字符串型返回值,如返回值为对 
     象,则自动转为json -->
    <bean id="mappingJacksonHttpMessageConverter"       
     class="org.springframework.http.converter
     .json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json; charset=UTF-8</value>
            <value>text/html; charset=UTF-8</value>
        </list>
    </property>
    </bean>
    <bean id="mappingStringHttpMessageConverter"
    class="org.springframework.http.converter.StringHttpMessageConverter" />

     <bean id="handleAdapter"
    class="org.springframework.web.servlet.mvc
    .annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 
     -->
        </list>
    </property>
    </bean>


    <!-- 设置返回字符串编码 -->  
    <bean class="org.springframework.web
   .servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
    <list>
        <!--json视图拦截器,读取到@ResponseBody的时候去配置它-->
        <ref bean="mappingJacksonHttpMessageConverter"/>
    </list>
    </property>
    </bean>  

    </beans>

Итак, что не так с моим файлом spring-servlet.xml? Любые предложения будут очень полезны!

...