[英]What is the difference between using @Qualifier annotation and directly injecting bean in spring?
Suppose I have a program 假设我有一个程序
@Component
public interface Coach{
public String giveCoaching();
}
@Component
public TennisCoach implements Coach{
@Override
public String giveCoaching(){
return "Teaching forhand";
}
}
I have two Demo classes in which I have injected the bean in different ways. 我有两个Demo类,以不同的方式注入了bean。 what is the difference in both the injections 两次注射有什么区别
public class AppDemo{
@AutoWired
@Qualifier("tennisCoach")
private Coach theCoach;
}
public class AppDemo{
@AutoWired
private TennisCoach tennisCoach;
}
}
When you have more than 1 implementation for you interface, you will get an exception when Autowiring the bean. 如果您的接口有多个实现,则在自动装配Bean时会出现异常。 At that time @Qualifier
will be used to choose the required implementation 届时,@ @Qualifier
将用于选择所需的实现
@Component
public interface Coach{
public String giveCoaching();
}
@Component
public TennisCoach implements Coach{
@Override
public String giveCoaching(){
return "Teaching forhand";
}
}
@Component
public CricketCoach implements Coach{
@Override
public String giveCoaching(){
return "Teaching forbat";
}
}
Now the ambiguity will occur when you autowire the Coach
Interface like below 现在,当您如下所示自动连接Coach
接口时,就会出现歧义
public class AppDemo{
@AutoWired
private Coach theCoach;
}
So you have to qualify the right bean for the Coach
Interface like below. 因此,您必须为Coach
接口定义合适的bean,如下所示。
public class AppDemo{
@AutoWired
@Qualifier("tennisCoach")
private Coach theCoach;
}
Alternatively you can use @Primary
annotation on top of any one of the implementation so that the Spring Container will by default choose the bean in case of more than 1 implementation for an interface. 或者,您可以在任何一种实现的顶部使用@Primary
批注,以便在默认情况下,如果一个接口的实现有多个,则Spring Container将选择Bean。
But in the code below, you are directly creating the object for the implementation rather than interface. 但是在下面的代码中,您将直接为实现而不是接口创建对象。
public class AppDemo{
@AutoWired
private TennisCoach tennisCoach;
}
}
当接口具有多个实现类时,将使用@Qualifier
批注。您应该选择要在Spring上下文中作为bean注入的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.