views:

563

answers:

1

I have this Spring config:

<bean id="boo" class="com.x.TheClass"/>

The class TheClass implements TheInterface. Then I have this (hypothetical) Java code:

@Autowired
TheInterface x;

@Autowired
TheClass y;

The autowiring of TheInterface works but the autowiring of TheClass fails. Spring gives me a NoSuchBeanDefinitionException for the class.

Why can you wire the interface and not the class?

+4  A: 

Normally, both will work, you can autowire interfaces or classes.

There's probably an autoproxy generator somewhere in your context, which is wrapping your boo bean in a generated proxy object. This proxy object will implement TheInterface, but will not be a TheClass. When using autoproxies, you need to program to the interface, not the implementation.

The likely candidate is transactional proxies - are you using Spring transactions, using AspectJ or @Transactional?

skaffman
lol, will you let me earn some points :)
ptomli
Yes, it does have `@Transactional`, sounds like this scenario is invalid..
Marcus
@Marcus: That's the problem then. If you use `@Transactional` and `<tx:annotation-driven/>`, you cannot cast the bean to `MyClass`, you have to use the interface.
skaffman