Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Autowiring class vs. interface?

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?

like image 819
Marcus Leon Avatar asked Mar 05 '10 14:03

Marcus Leon


People also ask

Can we use @autowired for interface?

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.

Which Autowiring is better in Spring?

1) byName autowiring mode It internally uses setter injection. But, if you change the name of bean, it will not inject the dependency.

Can we use @autowired in a class?

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.

What is difference between @autowired and @resource in Spring?

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.


1 Answers

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?

like image 71
skaffman Avatar answered Sep 20 '22 22:09

skaffman