无法使用服务类对象自动装配ServiceImpl类Bean

时间:2015-11-13 09:58:57

标签: java xml spring spring-mvc javabeans

我面临的错误如下:

    root cause

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginAndSignUpController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.frosters.firststep.service.LoginAndSignUpService com.frosters.firststep.controller.LoginAndSignUpController.loginAndSignUpService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.frosters.firststep.service.LoginAndSignUpService] 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)}
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)
root cause

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.frosters.firststep.service.LoginAndSignUpService com.frosters.firststep.controller.LoginAndSignUpController.loginAndSignUpService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.frosters.firststep.service.LoginAndSignUpService] 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)}
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:571)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)
root cause

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.frosters.firststep.service.LoginAndSignUpService] 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)}
    org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1326)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1072)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:967)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543)
    org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:667)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:633)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:681)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:552)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:493)
    org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
    javax.servlet.GenericServlet.init(GenericServlet.java:158)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

我已尝试使用@ Component,@ Service注释解决它,并尝试在XML配置中定义bean,如其他StackOverflow链接中所述,但我得到了相同的错误。可能是我没有做对,或者我做错了什么。

ControllerClass如下:

package com.frosters.firststep.controller;

@RequestMapping(value="/login.html")
@Controller
public class LoginAndSignUpController {

    @Autowired
    private LoginAndSignUpService loginAndSignUpService;

    @ModelAttribute("userVO")
    public UserVO createUserVOBean(){
        return new UserVO();
    }

    @RequestMapping(method=RequestMethod.GET)
    public ModelAndView getLoginForm(){
        System.out.println("inside getLoginForm() method");
        return new ModelAndView("Login");
    }

    @RequestMapping(method=RequestMethod.POST)
    public ModelAndView verifyLogin(@ModelAttribute("userVO")UserVO userVO){
        System.out.println("inside verifyLogin");
        boolean result = loginAndSignUpService.verifyUser(userVO);
        ModelAndView model;
        if(!result){
            model = new ModelAndView("Login");
            model.addObject("loginError", "invalid username/password");
        }
        else
            model = new ModelAndView("LoginSuccess"); //temporary view
        return model;
    }

}

ServiceImplClass如下:

package com.frosters.firststep.serviceimpl;

public class LoginAndSignUpServiceImpl implements LoginAndSignUpService{

    @Autowired
    private LoginAndSignUpDAO loginAndSignUpDAO;

    public boolean verifyUser(UserVO userVO) {
        boolean result = loginAndSignUpDAO.validateUser(userVO);
        if(result)
            return true;
        else
            return false;
    }

}

DAOImpl Class如下:

package com.frosters.firststep.daoimpl;

public class LoginAndSignUpDAOImpl extends NamedParameterJdbcDaoSupport implements LoginAndSignUpDAO{

    public boolean validateUser(UserVO userVO) {
        String userName = userVO.getUserName();
        String password = userVO.getPassword();
        SqlParameterSource paramSource = new MapSqlParameterSource("username", userName);
        try{
        String pass = this.getNamedParameterJdbcTemplate().queryForObject(FSUtils.LOGIN_INFO, paramSource, String.class);
        if(pass != null && !pass.isEmpty()){
            if(pass.equals(password))
                return true;
            else
                return false;
        }
        else
            return false;
    }catch(EmptyResultDataAccessException ex){
        return false;
        }
    }


    }

web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" 
    version="3.0">

  <display-name>Login And SignUp</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
  </context-param>

    <servlet>
        <servlet-name>spring-dispatcher-servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/classes/spring-dispatcher-servlet.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-dispatcher-servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

弹簧调度-servlet.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

        <context:component-scan base-package="com.frosters.firststep" />
        <mvc:annotation-driven />

        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/" />
            <property name="suffix" value=".jsp" />
        </bean>
</beans>

applicationContext.xml我已经定义了bean:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.2.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

        <context:property-placeholder location="classpath:DbUtil.properties"/>

        <!-- <context:component-scan base-package="com.frosters.firststep" />
        <mvc:annotation-driven /> -->

        <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.mysql.driverClassName}" />
            <property name="url" value="${jdbc.mysql.url}" />
            <property name="username" value="${jdbc.mysql.username}" />
            <property name="password" value="${jdbc.mysql.password}" />
        </bean>

        <bean id="loginAndSignUpDAO" class="com.frosters.firststep.daoimpl.LoginAndSignUpDAOImpl">
            <property name="dataSource" ref="dataSource" />
        </bean>

        <bean id="loginAndSignUpService" class="com.frosters.firststep.serviceimpl.LoginAndSignUpServiceImpl" />

</beans>

我已尝试在spring-dispatcher-servlet.xml中定义所有bean,但这样做也无法解决问题。

有人可以帮我看看哪里有错? ....谢谢......

3 个答案:

答案 0 :(得分:0)

在web.xml中添加ContextCLoaderListener

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

答案 1 :(得分:0)

Spring组件扫描将扫描您的基本包以查找用

注释的所有bean
  • @Repository(适用于DAO)
  • @Component
  • @Service(for Service)
  • @Controller(for Controller)

由于Spring没有为DAOImpl和ServiceImpl找到任何注释,因此它不会初始化它们,因为@Autowired不起作用,因为没有符合条件的候选者。

所以将@Repository添加到DaoImpl和@Service到ServiceImpl类,然后再试一次。

package com.frosters.firststep.serviceimpl;

@Service
public class LoginAndSignUpServiceImpl implements LoginAndSignUpService{

    @Autowired
    private LoginAndSignUpDAO loginAndSignUpDAO;

    public boolean verifyUser(UserVO userVO) {
        boolean result = loginAndSignUpDAO.validateUser(userVO);
        if(result)
            return true;
        else
            return false;
    }

}

package com.frosters.firststep.daoimpl;

@Repository
public class LoginAndSignUpDAOImpl extends NamedParameterJdbcDaoSupport implements LoginAndSignUpDAO{

    public boolean validateUser(UserVO userVO) {
        String userName = userVO.getUserName();
        String password = userVO.getPassword();
        SqlParameterSource paramSource = new MapSqlParameterSource("username", userName);
        try{
        String pass = this.getNamedParameterJdbcTemplate().queryForObject(FSUtils.LOGIN_INFO, paramSource, String.class);
        if(pass != null && !pass.isEmpty()){
            if(pass.equals(password))
                return true;
            else
                return false;
        }
        else
            return false;
    }catch(EmptyResultDataAccessException ex){
        return false;
        }
    }


   }

请尝试以下顺序

<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.frosters.firststep" /> 

<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.frosters.*" />

正如Imran在帖子中指出的那样(可能是主要原因),将上下文监听器放到你的web.xml

<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

答案 2 :(得分:0)

该行:

<context:component-scan base-package="com.frosters.firststep" />

应该在applicationContext.xml中,而不是在spring-dispatcher-servlet.xml中。