首先说明一下两个注解的作用
@Primary:在众多相同的bean中,优先选择用@Primary注解的bean(该注解加在各个bean上)
@Qualifier:在众多相同的bean中,@Qualifier指定需要注入的bean(该注解跟随在@Autowired后)
下面一个小例子:
1.ServiceTest接口
public interface ServiceTest {
void doSomething();
}2.两个实现类
@Service("service1")
public class Service1 implements ServiceTest{
@Override
public void doSomething() {
System.out.println("this is service1");
}
}@Service("service2")
public class Service2 implements ServiceTest{
@Override
public void doSomething() {
System.out.println("this is service2");
}
}3 测试一
@Autowired
private ServiceTest serviceTest;
@RequestMapping("showServiceTest")
public void showServiceTest(HttpServletRequest request, HttpServletResponse response) {
this.serviceTest.doSomething();
}启动报错org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'analysisTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.grac.web.controller.analysis.ServiceTest com.grac.web.controller.analysis.AnalysisTest.serviceTest; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.grac.web.controller.analysis.ServiceTest] is defined: expected single matching bean but found 2: service1,service2
4 测试二
@Autowired
@Qualifier("service2")
private ServiceTest serviceTest;
@RequestMapping("showServiceTest")
public void showServiceTest(HttpServletRequest request, HttpServletResponse response) {
this.serviceTest.doSomething();
}控制台输出
this is service2
在service1上加入@Primary注解
@Service("service1")
@Primary
public class Service1 implements ServiceTest{
@Override
public void doSomething() {
System.out.println("this is service1");
}
} @Autowired
private ServiceTest serviceTest;
@RequestMapping("showServiceTest")
public void showServiceTest(HttpServletRequest request, HttpServletResponse response) {
this.serviceTest.doSomething();
}控制台输出
this is service1
Spring注解@Primary与@Qualifier详解
本文通过实例详细解析了Spring框架中@Primary和@Qualifier注解的使用方法及区别。@Primary用于在存在多个相同类型的Bean时确定首选Bean;@Qualifier则允许开发者明确指定需要注入的Bean。
345

被折叠的 条评论
为什么被折叠?



