Reputation: 1521
I am working on a spring project that has the Service layer divided in two packages:
While calling methods declared in the interface and defined in the implementation, which of the two should be @Autowired
for which purpose?
What is the difference in autowiring the interface and the implementation?
I ask these keeping in mind that the point of this abstraction is usually to hide the declaration from the implementation
Upvotes: 0
Views: 935
Reputation: 795
As long as there is only a single implementation of the interface and that implementation is annotated with @Component
with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair.
Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier
annotation to inject the right implementation, along with @Autowired
annotation. If you are using @Resource
(J2EE), then you should specify the bean name using the name attribute of this annotation.
Normally, both will work, you can autowire interfaces or classes.
Upvotes: 1
Reputation: 368
You can always autowire interfaces, but if you are having multiple implementations of your interface then you will need to tell spring which implementation to consider, and there are multiple ways to do so.
Upvotes: 2