简体   繁体   中英

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:

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:

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

Here's a reference of the Spring Proxying Mechanism .

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.

I guess the actual type of your bean is obscured by dynamic proxy used to apply aspects. 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" ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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