Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC - How does @Autowired work?

I am working on a web application using Java and Spring. I'm new at Spring, so as an opportunity to learn, I was basically given an existing application and was told to extend it. I am having trouble understanding how the @Autowired work. I understand the high-level concept of dependency injection, but I want to know how the @Autowired annotation knows which concrete implementation of an interface to inject?

To put my question into context, I will explain the problem I am having:

I have an interface called PostDao, and a class called PostDaoImpl which implements PostDao. I then have another class called PostDaoPublicImpl which extends PostDaoImpl. These classes exist in my persistence layer.

I then have an interface called PostService, and a class called called PostServiceImpl which implement PostService. I then have another class called PostServicePublicImpl which extends PostServiceImpl. These classes exist in my services layer.

In PostServiceImpl the following line injects the following object:

@Autowired private PostDao postDao; 
//This injects an object of the class PostDaoImpl

My problem is, in PostServicePublicImpl how do I have the same declaration as above, but have it inject an object of the class PostDaoPublicImpl:

@Autowired private PostDao postDao; 
//This injects an object of the class PostDaoPublicImpl

I feel as though if I understand how the @Autowired annotation works, then I will be able to solve this problem. Any help and suggestions to solve the problem would be greatly appreciated.

like image 484
COBOL Avatar asked Oct 02 '22 19:10

COBOL


2 Answers

First of all you need to understand how Autowiring works

then in the bean definition, define autowire strategy - let it be byName for our case

<bean id="postDaoPublicImpl" class="com.yourpackage.PostDaoPublicImpl" autowire="byName" />

that means, if any class has a property with name "postDaoPublicImpl", which is the bean id of above bean, will be automatically injected with the bean instance

after that in your class PostServicePublicImpl define property like this

class PostServicePublicImpl  {

@Autowired private PostDaoPublicImpl postDaoPublicImpl; 
//here Spring will auto inject PostDaoPublicImpl implementation, since this property name matches the bean id and (auto wiring strategy is "byName")

}
like image 96
sanbhat Avatar answered Oct 05 '22 10:10

sanbhat


I found an easier solution to my problem. Using the @Qualifier tag I can give a unique name to each implementation of the interface. Then when auto-wiring the object, I just provide a qualifier and the object of the implementation matching the qualifier is injected.

like image 23
COBOL Avatar answered Oct 05 '22 10:10

COBOL