In previous post under Spring Core, I showed with example how to use “@Qualifier” annotation with “@Bean” annotation.
In this post under Spring Core, I will show with example how to use “@Qualifier” annotation with “@Component” annotation.
For our example I will create an interface named “IMovie” as shown below
IMovie
package core.package44;
public interface IMovie {
public void display();
}
I have created two classes that implement the above interface named “ComedyMovie” and “ActionMovie”.
ComedyMovie
package core.package44;
import org.springframework.stereotype.Component;
@Component
public class ComedyMovie implements IMovie {
@Override
public void display() {
System.out.println("Comedy Movie");
}
}
ActionMovie
package core.package44;
import org.springframework.stereotype.Component;
@Component
public class ActionMovie implements IMovie {
@Override
public void display() {
System.out.println("Action Movie");
}
}
Please note, the classes are marked with “@Component” without any custom name. So the classname itself is the component name.
So the component name for “ComedyMovie” will be “comedyMovie” and the component name for “ActionMovie” will be “actionMovie”.
Now I will show the main class where I will use “@Qualifier” annotation.
Main class
package core.package44;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "core.package44")
public class Example44 {
@Autowired
@Qualifier("comedyMovie")
private IMovie movie;
public static void main(String[] args) {
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example44.class);
Example44 example44 = applicationContext.getBean(Example44.class);
example44.movie.display();
}
}
In the above code, I created an instance variable named “movie” marked it with “@Autowired” and “@Qualifier” annotation. Refer from line 13 to 15.
The argument to “@Qualifier” annotation is the component name which in this case is “comedyMovie”.
So Spring will first come up with list of classes that implement “IMovie” interface and then out of them search for class whose component name is “comedyMovie”, which in this case is class named “ComedyMovie” and create an instance of “ComedyMovie” class and assign it to “movie” variable.
In this way we can use “@Qualifier” annotation with “@Component” annotation.