简体   繁体   English

Spring Autowire表现异常

[英]Spring autowire not behaving as expected

I have tried to autowire a bean for a test class using @Autowire , however the bean is not wired and I get this exception: 我试图使用@Autowire为测试类自动装配一个bean,但是该bean未@Autowire ,并且出现以下异常:

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

My test class looks like this: 我的测试课看起来像这样:

package com.abc;

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

    @Autowired
    private MyDaoHibernateImpl myDao;

    ....
}

The applicationContext.xml file has this bean definition: applicationContext.xml文件具有以下bean定义:

<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. 在此先感谢您的任何建议。

--James - 詹姆士

As axtavt suggests , spring is a framework that heavily favors the use of interfaces. 正如axtavt所建议的那样 ,spring是一个非常赞成使用接口的框架。 A spring best practice is to define a dependency to an interface and let spring inject the implementation. Spring的最佳实践是定义对接口的依赖关系,并让Spring注入实现。 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. 但是类不应该知道其依赖项的实现细节。

Here's a reference of the Spring Proxying Mechanism . 这是Spring Proxying机制的参考。

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. 关于使用接口的一般概念,您应该阅读Joshua Bloch撰写的Effective Java ,第8章,第52项:按对象的接口引用对象。 Also, you should read Interfaces and Inheritance from the Sun Java Tutorial. 另外,您还应该阅读《 Sun Java教程》中的“ 接口和继承 ”。

I guess the actual type of your bean is obscured by dynamic proxy used to apply aspects. 我猜您的bean的实际类型被用于应用方面的动态代理所遮盖。 In this case you need to use interface rather than class for autowired fields (or force target class proxy strategy with proxy-target-class="true" ). 在这种情况下,您需要对自动连接的字段使用接口而不是类(或使用proxy-target-class="true"强制目标类代理策略)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM