【问题标题】:Could not autowire field in spring. why?无法在春季自动装配字段。为什么?
【发布时间】:2012-08-10 20:55:59
【问题描述】:

我不断收到此错误,但不知道为什么.. 是的,我知道很多人有类似的问题,但阅读他们得到的答案并不能解决我的问题。

org.springframework.beans.factory.BeanCreationException:创建名为“contactController”的bean时出错:注入自动装配的依赖项失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法自动装配字段:私有 net.service.ContactService net.controller.ContactController.contactService;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有为依赖项找到类型为 [net.service.ContactService] 的匹配 bean:预计至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

这里是控制器:

@Controller
@SessionAttributes
public class ContactController {

    @Autowired
    private ContactService contactService;
//methods...


}

ContactServiceImpl

@Service("contactService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ContactServiceImpl implements ContactService {

    @Autowired
    private ContactDao contactDao;

    public ContactServiceImpl() {
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void addContact(Contact contact) {
        contactDao.saveContact(contact);
    }

    @Override
    public List<Contact> getContacts() {
        return contactDao.getAllContacts();
    }

}

ContactDaoImpl

@Repository("contactDao")
public class ContactDaoImpl implements ContactDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void saveContact(Contact contact) {
        sessionFactory.getCurrentSession().saveOrUpdate(contact);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Contact> getAllContacts() {
        return (List<Contact>) sessionFactory.getCurrentSession().createQuery("from contact c").list();
    }

}

和 spring-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:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <context:property-placeholder location="classpath:jdbc.properties" />
    <context:component-scan base-package="net.controller" />


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

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

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

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>net.form.Contact</value>
            </list>
        </property>


        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans>

【问题讨论】:

  • 那么你有contactService字段的setter方法吗?
  • @sundar 您不需要该字段的 setter 方法才能使 Spring 注入工作。无论如何,这里的问题显然是,据 Spring 所知,要注入的 bean 没有找到,而不是找到但无法注入。
  • @DaveNewton:嗯,你说得对,我写了一个很长的答案,根本没有提到这一点。是的,如果包含 ContactServiceImpl 的包不在声明为可注释可扫描的包中,则该 bean 将不会被创建,因此无法在其他 bean 中注入
  • 解决了 Pyranja 下面建议的问题
  • @pr123 正如我在之前的评论中所建议的那样。

标签: java exception spring-mvc


【解决方案1】:

我今天也遇到了同样的问题。原来是我忘记为我的服务实现文件提及@Service/@Component 注释,spring 无法自动装配并且无法创建 bean。

【讨论】:

    【解决方案2】:

    ContactServiceImpl bean 的创建存在问题。首先,在启动 Spring 上下文并创建 ContactController 的实例时,通过调试无参数构造函数来确保该类实际实例化。

    如果 ContactServiceImpl 实际上是由 Spring 上下文实例化的,但它与您的 @Autowire 注释根本不匹配,请尝试在您的注释注入中更加明确。这是一个与您处理类似问题并提供一些可能解决方案的人:

    http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/

    如果你问我,我想你换掉就可以了

    @Autowired
    private ContactService contactService;
    

    与:

    @Resource
    @Qualifier("contactService")
    private ContactService contactService;
    

    【讨论】:

      【解决方案3】:

      在 java config 中,确保你已经像这样在 RootConfig 中导入你的配置 @Import(PersistenceJPAConfig.class)

      【讨论】:

        【解决方案4】:

        当您收到此错误时,缺少一些注释。 我在服务上缺少@service 注释。当我添加该注释时,它对我来说效果很好。

        【讨论】:

          【解决方案5】:

          我遇到了完全相同的问题 尝试将两个类放在同一个包中,并在 pom.xml 中添加一行

          <dependency> 
                      <groupId> org.springframework.boot </groupId> 
                      <artifactId> spring-boot-starter-web </artifactId> 
                      <version> 1.2.0.RELEASE </version> 
          </dependency>
          

          【讨论】:

            【解决方案6】:

            我遇到了同样的错误,搜索它把我带到了这里。我的解决方法似乎只是将 @Component 注释添加到抽象服务的实现中。

            在这种情况下,它看起来像:

            import org.springframework.stereotype.Component;
            
            ...
            
            @Component
            public class ContactServiceImpl implements ContactService {
            

            【讨论】:

              【解决方案7】:

              在 spring servlet .xml 中:

              <context:component-scan base-package="net.controller" />
              

              (我假设服务实现与服务接口“net.service”在同一个包中)

              我认为您必须将包 net.service(或全部网络)添加到组件扫描中。目前 spring 仅在 net.controller 中搜索组件,并且由于您的服务 impl 在 net.service 中,因此它不会被 spring 实例化。

              【讨论】:

              • 是的,这是个好主意。
              • 我错误地将服务保存到其他包中,效果很好。谢谢。
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2013-04-26
              • 2019-08-02
              • 2017-12-13
              • 1970-01-01
              • 2015-12-11
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多