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?
If you try to use @Autowired on an interface, the Spring framework would throw an exception as it won't be able to decide which implementation class to use.
1) byName autowiring mode It internally uses setter injection. But, if you change the name of bean, it will not inject the dependency.
We can also use @Autowired annotation on constructor for constructor based spring autowiring. For @Autowired annotation to work, we also need to enable annotation based configuration in spring bean configuration file. This can be done by context:annotation-config element or by defining a bean of type org.
The main difference is is that @Autowired is a spring annotation whereas @Resource is specified by the JSR-250. So the latter is part of normal java where as @Autowired is only available by spring.
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
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With