Spring注释自动装配|预计至少有1个豆有资格成为autowire候选人

时间:2015-07-24 08:28:59

标签: spring annotations autowired

我的webapp中有自动装配问题。 我的项目有文件:

UserDAO的

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;
    }
}

在UserDAOImpl

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;

}

UserService

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();
        }

    }

}

UserServiceImpl

<?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>

hibernate.crg.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>

spring_cfg.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>

MVC-调度-servlet.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>

根context.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>

的web.xml

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";
    }

}

UserSelectionTestPageController

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$1.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)

我不知道问题的根源。我正在做我喜欢的朋友项目。互联网没有答案,请帮忙。

堆栈

<?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>

的web.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>

根context.xml中

Iterator

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

3 个答案:

答案 0 :(得分:0)

您只需将web.xml更新为以下(请注意,在调度程序servlet中<{1}}

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:annotation-configmvc:annotation-driven来整理您的配置。 (请参阅herehere了解

建议阅读Difference between *Context.xml and *-servlet.xml in Spring

答案 1 :(得分:0)

您的控制器组件和服务/ DAO组件正在不同的上下文中实例化。更新您的调度程序servlet以扫描整个项目,您应该全部设置:

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

答案 2 :(得分:0)

如果您认为项目配置正确并且遇到此类问题,请查看 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>

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

非常感谢您的帮助。 =]