Spring autowire doesn't behave as expected

I tried an autowire bean for the test class using @Autowire , however the bean is not connected, 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 is as follows:

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

Thanks in advance for any suggestions.

- james

+1
java spring dependency-injection autowired
source share
2 answers

As axtavt suggests , spring is a framework that greatly facilitates the use of interfaces. A spring Best practice is to define an interface dependency and let spring implement the implementation. What the whole point of dependency injection is: you specify the interface you need, but the container will enter the implementation class that it selects, which can be either the class you created or the dynamic proxy based on this class. But the class does not need to know the implementation details of this dependency.

Here's a link to the Spring Proxy Engine .

You should read About the General Concept of Using Interfaces Effective Java by Joshua Bloch , chapter 8, paragraph 52: access objects by their interfaces. In addition, you should read Interfaces and Inheritance from the Sun Java tutorial.

+1
source share

I assume that the actual type of your bean is hidden by the dynamic proxy used to apply the aspects. In this case, you need to use the interface, not the class for fields with auto-programming (or force the proxy strategy of the target class with proxy-target-class="true" ).

0
source share

All Articles