Spring 注释自动装配 |预计至少有 1 个符合自动装配候选条件的 bean

Spring annotation autowired | expected at least 1 bean which qualifies as autowire candidate

我的 web 应用程序中的自动装配有问题。 我的项目中有文件:

UserDAO

package com.mmsystem.dao.interfaces;

import com.mmsystem.model.Invitation;
import com.mmsystem.model.Meeting;
import com.mmsystem.model.User;
import com.mmsystem.model.Request;

import java.util.List;

public interface UserDAO {
    public Long addUser(User user);

    public User getUser(Long id);

    public void deleteUser(Long id);

    public List<User> getAllUsers();

    public List<Meeting> getUserMeetings(Long idUser);

    public List<Request> getUserRequests(Long idUser);

    public List<Invitation> getUserInvitations(Long idUser);
}

UserDAOimpl

package com.mmsystem.dao.impl;

import com.mmsystem.hibernate.HibernateUtil;
import com.mmsystem.dao.interfaces.UserDAO;
import com.mmsystem.model.Invitation;
import com.mmsystem.model.Meeting;
import com.mmsystem.model.Request;
import com.mmsystem.model.User;
import org.hibernate.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDAOimpl implements UserDAO {
    Session currentSession;

    public Long addUser(User user) {

        currentSession = HibernateUtil.getSessionFactory().openSession();
        currentSession.beginTransaction();

        currentSession.save(user);
        Long id = user.getIdUser();

        currentSession.getTransaction().commit();
        currentSession.close();
        return id;
    }

    public User getUser(Long id) {
        currentSession = HibernateUtil.getSessionFactory().openSession();

        User user = (User) currentSession.get(User.class, id);

        currentSession.close();
        return user;
    }

    public void deleteUser(Long id) {
        currentSession = HibernateUtil.getSessionFactory().openSession();
        currentSession.beginTransaction();

        User user = (User) currentSession.get(User.class, id);

        if(user != null){
            currentSession.delete(user);
        }

        currentSession.getTransaction().commit();
        currentSession.close();
    }

    public List<User> getAllUsers() {
        currentSession = HibernateUtil.getSessionFactory().openSession();

        try{
            List<User> list = currentSession.createQuery("FROM User").list();
            return list;
        }catch(HibernateException e){
            e.printStackTrace();
        }finally {
            currentSession.close();
        }

        return null;
    }

    public List<Meeting> getUserMeetings(Long idUser) {
        currentSession = HibernateUtil.getSessionFactory().openSession();
        try{
            Query query = currentSession.createQuery("FROM Meeting where owner.idUser = :idUser");
            query.setParameter("idUser", idUser.longValue());
            List<Meeting> meetingList = query.list();

            return meetingList;
        }catch(HibernateException e){
            e.printStackTrace();
        }finally {
            currentSession.close();
        }

        return null;
    }

    public List<Request> getUserRequests(Long idUser) {
        currentSession = HibernateUtil.getSessionFactory().openSession();
        try{
            Query query = currentSession.createQuery("FROM Request where owner.idUser = :idUser");
            query.setParameter("idUser",idUser);
            List<Request> requestList = query.list();

            return requestList;
        }catch(HibernateException e){
            e.printStackTrace();
        }finally {
            currentSession.close();
        }

        return null;
    }

    public List<Invitation> getUserInvitations(Long idUser) {
        currentSession = HibernateUtil.getSessionFactory().openSession();
        try{
            Query query = currentSession.createQuery("FROM Invitation where invitedUser.idUser = :idUser");
            query.setParameter("idUser", idUser);
            List<Invitation> invitationList = query.list();

            return invitationList;
        }catch(HibernateException e){
            e.printStackTrace();
        }finally {
            currentSession.close();
        }

        return null;
    }
}

用户服务

package com.mmsystem.service.interfaces;

import com.mmsystem.model.Invitation;
import com.mmsystem.model.Meeting;
import com.mmsystem.model.Request;
import com.mmsystem.model.User;
import com.mmsystem.service.exceptions.NoSuchObjectException;
import com.mmsystem.service.exceptions.RequiredFildEmptyException;
import com.mmsystem.service.exceptions.ObjectAlreadyExistsException;
import org.springframework.stereotype.Component;

import java.util.List;
@Component("userService")
public interface UserService {

    public List<User> getAllUsers();

    public User getUser(Long id) throws NoSuchObjectException;

    public Long addUser(User user) throws RequiredFildEmptyException, ObjectAlreadyExistsException;

    public void deleteUser(Long id) throws NoSuchObjectException;

    public List<Meeting> getUserMeetings(Long idUser) throws NoSuchObjectException;

    public List<Request> getUserRequests(Long idUser) throws NoSuchObjectException;

    public List<Invitation> getUserInvitations(Long idUser) throws NoSuchObjectException;

}

UserServiceImpl

package com.mmsystem.service.impl;

import com.mmsystem.dao.interfaces.UserDAO;
import com.mmsystem.model.Invitation;
import com.mmsystem.model.Meeting;
import com.mmsystem.model.Request;
import com.mmsystem.model.User;
import com.mmsystem.service.exceptions.NoSuchObjectException;
import com.mmsystem.service.exceptions.RequiredFildEmptyException;
import com.mmsystem.service.exceptions.ObjectAlreadyExistsException;
import com.mmsystem.service.interfaces.UserService;
import org.hibernate.HibernateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    public List<User> getAllUsers() {
        return userDAO.getAllUsers();
    }

    public User getUser(Long id) throws NoSuchObjectException {

        if(id == null){
            throw new NullPointerException();
        }

        try {
            User user = userDAO.getUser(id);
            return user;
        }catch (HibernateException ex){
            throw new NoSuchObjectException();
        }
    }

    public Long addUser(User user) throws RequiredFildEmptyException, ObjectAlreadyExistsException {

        if(user == null){
            throw new NullPointerException();
        }

        if(user.getIsAdmin() == null ||
                user.getIsBanned() == null ||
                user.getLogin() == null ||
                user.getName() == null ||
                user.getPassword() == null ||
                user.getSurname() == null){

            throw new RequiredFildEmptyException();
        }

        try{
            Long id = userDAO.addUser(user);
            return id;
        }catch (HibernateException ex){
            throw new ObjectAlreadyExistsException();
        }

    }

    public void deleteUser(Long id) throws NoSuchObjectException {
        if(id == null){
            throw new NullPointerException();
        }

        try {
            userDAO.deleteUser(id);
        }catch (HibernateException ex){
            throw new NoSuchObjectException();
        }
    }

    public List<Meeting> getUserMeetings(Long id) throws NoSuchObjectException {
        if(id == null){
            throw new NullPointerException();
        }

        try{
            return userDAO.getUserMeetings(id);
        }catch (HibernateException ex){
            throw new NoSuchObjectException();
        }

    }

    public List<Request> getUserRequests(Long id) throws NoSuchObjectException {
        if(id == null){
            throw new NullPointerException();
        }

        try{
            return userDAO.getUserRequests(id);
        }catch (HibernateException ex){
            throw new NoSuchObjectException();
        }

    }

    public List<Invitation> getUserInvitations(Long id) throws NoSuchObjectException {
        if(id == null){
            throw new NullPointerException();
        }

        try{
            return userDAO.getUserInvitations(id);
        }catch (HibernateException ex){
            throw new NoSuchObjectException();
        }

    }

}

hibernate.crg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/meetingmaker_db</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">art5126</property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">3</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">update</property>

        <mapping class="com.mmsystem.model.User"/>
        <mapping class="com.mmsystem.model.Meeting"/>
        <mapping class="com.mmsystem.model.Request"/>
        <mapping class="com.mmsystem.model.Invitation"/>

    </session-factory>
</hibernate-configuration>

spring_cfg.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

</beans>

mvc-调度程序-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

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

    <mvc:annotation-driven />
    <context:annotation-config />
    <context:component-scan base-package="com.mmsystem.web.controllers"/>

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


</beans:beans>

root-context.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:annotation-config />

    <context:component-scan base-package="com.mmsystem.dao.impl"/>
    <context:component-scan base-package="com.mmsystem.service.impl"/>

</beans>

web.xml

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

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

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

</web-app>

UserSelectionTestPageController

package com.mmsystem.web.controllers;

import com.mmsystem.model.User;
import com.mmsystem.service.interfaces.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;


@Controller
public class UserSelectionPageTestController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = {"/"}, method = { RequestMethod.GET})
    public String userSelectionPage(ModelMap model){

        List<User> userList = userService.getAllUsers();

        model.put("userList", userList);

        return "userSelection";
    }

}

我不知道问题的根源。我所做的一切都和我朋友的项目一样。网上没有答案,求助。

堆栈

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userSelectionPageTestController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mmsystem.service.interfaces.UserService com.mmsystem.web.controllers.UserSelectionPageTestController.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mmsystem.service.interfaces.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)}
    org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
    org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
    org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:303)
    org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
    org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
    org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
    org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
    org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
    org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
    org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
    org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
    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:957)
    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:620)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2476)
    org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2465)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    java.lang.Thread.run(Thread.java:745)

已添加

web.xml

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

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

</web-app>

root-context.xml

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       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-4.0.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">


    <context:component-scan base-package="com.mmsystem.dao.impl"/>
    <context:component-scan base-package="com.mmsystem.service.impl"/>

</beans>

已添加

完整堆栈跟踪 http://pastebin.com/HBRAUja3

您只需将 web.xml 更新为以下内容(请注意,在 dispathcer servlet 中不需要 contextConfigLocation

<servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

另外,在使用 context:component-scan 时,您可以通过从相应文件中删除多余的 context:annotation-configmvc:annotation-driven 来整理您的配置。 (请参阅 here and here 了解说明

推荐阅读Difference between *Context.xml and *-servlet.xml in Spring

您的控制器组件和 service/DAO 组件正在不同的上下文中实例化。更新您的调度程序 servlet 以扫描整个项目,您应该已准备就绪:

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

如果您认为您的项目配置正确并且遇到这样的问题 - 请查看您的 pom.xml 文件以获取依赖项版本。他们中的一些人可能会产生冲突,就像他们在我的网络应用程序中所做的那样。您还可以使用 properties 标记在 pom.xml 文件的顶部获取依赖项版本。例如,您可以看到我的新 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.meetingmakersystem</groupId>
    <artifactId>meetingmaker</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <springframework.version>4.0.6.RELEASE</springframework.version>
        <hibernate.version>4.3.6.Final</hibernate.version>
        <mysql.connector.version>5.1.31</mysql.connector.version>
        <jstl.version>1.2</jstl.version>
    </properties>

    <dependencies>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${springframework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${springframework.version}</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
        </dependency>

        <!--JSTL-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl.version}</version>
            <scope>provided</scope>
        </dependency>


    </dependencies>

    <build>
        <resources>
            <resource>
                <filtering>true</filtering>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
        <finalName>MeetingMaker</finalName>
    </build>
</project>

我的项目现在还有其他错误,但我想,我可以自己解决。

非常感谢您的帮助。 =]