Spring Autowire表现异常 [英] Spring autowire not behaving as expected

查看:113
本文介绍了Spring Autowire表现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用@Autowire为测试类自动装配bean,但是未连接bean,但出现此异常:

I have tried to autowire a bean for a test class using @Autowire, however the bean is not wired and I get this exception:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
    No matching bean of type [com.abc.MyDaoHibernateImpl] 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)}

我的测试类如下:

package com.abc;

@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
@TransactionConfiguration(transactionManager = "hibernateTransactionManager")
public class MyDaoHibernateImplTest
    extends AbstractTransactionalJUnit4SpringContextTests
{

    @Autowired
    private MyDaoHibernateImpl myDao;

    ....
}

applicationContext.xml文件具有以下bean定义:

The applicationContext.xml file has this bean definition:

<bean id="myDao" class="com.abc.MyDaoHibernateImpl">
    <property name="sessionFactory" ref="hibernateSessionFactory" />
</bean>

谁能看到我要去哪里错了?

Can anyone see where I'm going wrong?

提前感谢您的任何建议.

Thanks in advance for any suggestions.

-詹姆斯

推荐答案

As axtavt suggests, spring is a framework that heavily favors the use of interfaces. A spring best practice is to define a dependency to an interface and let spring inject the implementation. That's the whole point of dependency injection: you specify the interface you need, but the container will inject the implementation class it selects, which can either be a class you created or a dynamic proxy based on this class. But a class should not know the implementation details of it's dependency.

以下是关于使用接口的一般概念,您应该阅读Joshua Bloch撰写的有效的Java ,第8章,第52项:通过其接口引用对象.另外,您还应该从Sun Java阅读接口和继承教程.

About the general concept of using interfaces, you should read Effective Java by Joshua Bloch, Chapter 8, Item 52: Refer to objects by their interfaces. Also, you should read Interfaces and Inheritance from the Sun Java Tutorial.

这篇关于Spring Autowire表现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆