注入自动连接的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段

时间:2016-06-16 15:51:40

标签: spring hibernate

运行我的代码时出错。

错误讯息:

  

输入例外报告

     用于servlet mvc-dispatcher的

消息Servlet.init()抛出异常

     

description服务器遇到阻止它的内部错误   完成此请求。

     

例外

     

javax.servlet.ServletException:Servlet的Servlet.init()   mvc-dispatcher抛出异常     org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)     org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)     org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)     org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)     org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)     org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:672)     org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1520)     org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1476)     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)

     

org.springframework.beans.factory.BeanCreationException:错误   用name' tipoSanguineoController创建bean&#39 ;:注入   自动连接依赖失败;嵌套异常是   org.springframework.beans.factory.BeanCreationException:不能   autowire字段:私有   br.inf.datus.ifisio.service.TipoSanguineoService   br.inf.datus.ifisio.controller.TipoSanguineoController.tipoSanguineoService;   嵌套异常是   org.springframework.beans.factory.BeanCreationException:错误   创建名为' tipoSanguineoServiceImpl'的bean在文件中定义   [d:\ projetos \ ifisio \目标\ ifisio \ WEB-INF \类\ BR \ INF \大督\ ifisio \服务\ TipoSanguineoServiceImpl.class]:   bean的实例化失败;嵌套异常是   org.springframework.beans.BeanInstantiationException:失败   实例化[br.inf.datus.ifisio.service.TipoSanguineoServiceImpl]:否   找到默认构造函数;嵌套异常是   java.lang.NoSuchMethodException:   br.inf.datus.ifisio.service.TipoSanguineoServiceImpl。()     org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)     org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)     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:502)     org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)     org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)     org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)     org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)     org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:672)     org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1520)     org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1476)     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)

     

根本原因

     

org.springframework.beans.factory.BeanCreationException:无法   autowire字段:私有   br.inf.datus.ifisio.service.TipoSanguineoService   br.inf.datus.ifisio.controller.TipoSanguineoController.tipoSanguineoService;   嵌套异常是   org.springframework.beans.factory.BeanCreationException:错误   创建名为' tipoSanguineoServiceImpl'的bean在文件中定义   [d:\ projetos \ ifisio \目标\ ifisio \ WEB-INF \类\ BR \ INF \大督\ ifisio \服务\ TipoSanguineoServiceImpl.class]:   bean的实例化失败;嵌套异常是   org.springframework.beans.BeanInstantiationException:失败   实例化[br.inf.datus.ifisio.service.TipoSanguineoServiceImpl]:否   找到默认构造函数;嵌套异常是   java.lang.NoSuchMethodException:   br.inf.datus.ifisio.service.TipoSanguineoServiceImpl。()     org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor $ AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)     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:1202)     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:502)     org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)     org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)     org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)     org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)     org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:672)     org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1520)     org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1476)     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)

和我的档案:

的web.xml

<web-app version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>x</display-name>

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

MVC-调度-servlet.xml中

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

  <context:annotation-config/>

  <context:component-scan base-package="br.inf.datus.ifisio"/>

  <mvc:annotation-driven/>

  <!-- Database properties -->
  <context:property-placeholder location="classpath:application.properties"/>

  <!-- Resource location to load JS, CSS, Images etc -->
  <mvc:resources mapping="/resources/**" location="/resources/"/>

  <!--Prevent browsers from caching contents except the static resources content-->
  <mvc:interceptors>
    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
      <property name="paramName" value="lang"/>
    </bean>
    <mvc:interceptor>
      <mvc:mapping path="/**"/>
      <mvc:exclude-mapping path="/resources/**"/>
      <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor">
        <property name="cacheSeconds" value="0"/>
        <property name="useExpiresHeader" value="true"/>
        <property name="useCacheControlHeader" value="true"/>
        <property name="useCacheControlNoStore" value="true"/>
      </bean>
    </mvc:interceptor>
  </mvc:interceptors>

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

  <!-- DataSource -->
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="${db.driverClassName}"/>
    <property name="jdbcUrl" value="${db.url}"/>
    <property name="user" value="${db.username}"/>
    <property name="password" value="${db.password}"/>

    <property name="acquireIncrement" value="${conn.acquireIncrement}"/>
    <property name="minPoolSize" value="${conn.minPoolSize}"/>
    <property name="maxPoolSize" value="${conn.maxPoolSize}"/>
    <property name="maxIdleTime" value="${conn.maxIdleTime}"/>
  </bean>

  <!-- Hibernate SessionFactory -->
  <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
      <props>
        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
        <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
        <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
        <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
      </props>
    </property>
    <property name="packagesToScan" value="br.inf.datus.ifisio.persistence.entity"/>
  </bean>

  <!-- Transaction -->
  <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
  </bean>

  <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

GenericDaoImpl

    package br.inf.datus.ifisio.persistence.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.inf.datus.ifisio.persistence.dao.GenericDao;

@Repository
public abstract class GenericDaoImpl<E, K extends Serializable> implements GenericDao<E, K> {

    @Autowired
    private SessionFactory sessionFactory;

    protected Class<? extends E> daoType;

    @SuppressWarnings("unchecked")
    public GenericDaoImpl() {
        Type t = getClass().getGenericSuperclass();
        ParameterizedType pt = (ParameterizedType) t;
        daoType = (Class) pt.getActualTypeArguments()[0];
    }

    protected Session currentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void add(E entity) {
        currentSession().save(entity);
    }

    @Override
    @SuppressWarnings("unchecked")
    public E findById(K key) {
        return (E) currentSession().get(daoType, key);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<E> getAll() {
        return currentSession().createCriteria(daoType).list();
    }

    @Override
    public void update(E entity) {
        currentSession().saveOrUpdate(entity);
    }

    @Override
    public void remove(E entity) {
        currentSession().delete(entity);
    }

    @Override
    public void saveOrUpdate(E entity) {
        currentSession().saveOrUpdate(entity);
    }  
}

GenericServiceImpl

    package br.inf.datus.ifisio.service;

import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.inf.datus.ifisio.persistence.dao.GenericDao;

@Service
public abstract class GenericServiceImpl<E, K> implements GenericService<E, K> {

    private GenericDao<E, K> genericDao;

    public GenericServiceImpl(GenericDao<E,K> genericDao) {
        this.genericDao=genericDao;
    }

    public GenericServiceImpl() {

    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void add(E entity) {
        genericDao.add(entity);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public E findById(K id) {
        return genericDao.findById(id);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = true)
    public List<E> getAll() {
        return genericDao.getAll();
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void remove(E entity) {
        genericDao.remove(entity);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void saveOrUpdate(E entity) {
        genericDao.saveOrUpdate(entity);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void update(E entity) {
        genericDao.update(entity);
    }
}

TipoSanguineoDaoImpl

package br.inf.datus.ifisio.persistence.dao;

import br.inf.datus.ifisio.persistence.entity.TipoSanguineo;
import org.springframework.stereotype.Repository;

@Repository
public class TipoSanguineoDaoImpl extends GenericDaoImpl<TipoSanguineo, Long> implements TipoSanguineoDao {

}

TipoSanguineoServiceImpl

package br.inf.datus.ifisio.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import br.inf.datus.ifisio.persistence.dao.GenericDao;
import br.inf.datus.ifisio.persistence.dao.TipoSanguineoDao;
import br.inf.datus.ifisio.persistence.entity.TipoSanguineo;

@Service
public class TipoSanguineoServiceImpl extends GenericServiceImpl<TipoSanguineo, Long> implements TipoSanguineoService {

    @Autowired
    private final TipoSanguineoDao tipoSanguineoDao;

    public TipoSanguineoServiceImpl(@Qualifier("tipoSanguineoDaoImpl") GenericDao<TipoSanguineo, Long> genericDao) {
        super(genericDao);
        this.tipoSanguineoDao = (TipoSanguineoDao) genericDao;
    } 
}

2 个答案:

答案 0 :(得分:1)

答案就在堆栈跟踪中:

Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [br.inf.datus.ifisio.service.TipoSanguineoServiceImpl]: No default constructor found;

您已在该类中指定了字段注入(字段@Autowired上的tipoSanguineoDao注释)但您未提供默认(无参数)构造函数。看起来你想要构造函数注入(在构造函数参数上有一个@Qualifier注释的事实证明),但这与字段注入冲突。

@Autowired注释移动到构造函数。

答案 1 :(得分:0)

看起来你正在尝试做基于构造函数的依赖注入.. TipoSanguineoServiceImpl下面的更改应该可以解决您的问题。

@Autowired
public TipoSanguineoServiceImpl(@Qualifier("tipoSanguineoDaoImpl") GenericDao<TipoSanguineo, Long> genericDao) {
            super(genericDao);
            this.tipoSanguineoDao = (TipoSanguineoDao) genericDao;
        }