当Spring中存在一个接口(或抽象类)有多个实现类时,我们可以使用@Qualifier
注解来指定要注入的实现类。本文将介绍在这种情况下如何正确注入Service的多个实现类,以下是相关内容的整理:
本文将探讨在Spring应用中,当一个Service接口有多个实现类时,如何通过使用@Qualifier
注解来正确地注入所需的实现类。
在使用Spring框架开发应用程序时,很常见一个接口拥有多个不同的实现类。这样的情况在需要根据不同的业务逻辑或需求来选择不同的实现时很有用。通过正确注入所需的实现类,我们可以实现更好的代码组织和可维护性。
使用@Qualifier
注解是解决这个问题的主要方法。它允许我们在需要注入的地方指定要使用的具体实现类。
在Service接口上使用@Qualifier
注解: 在多个实现类中,给每个实现类添加一个唯一的标识,然后在Service接口的注入点上使用@Qualifier
注解,并指定要注入的实现类的标识。
public interface MyService { ... }
@Service("serviceImpl1")
public class MyServiceImpl1 implements MyService { ... }
@Service("serviceImpl2")
public class MyServiceImpl2 implements MyService { ... }
在注入点使用@Qualifier
注解: 在需要使用MyService
的地方,使用@Autowired
和@Qualifier
注解来注入特定的实现类。
@Autowired
@Qualifier("serviceImpl1")
private MyService myService;
Controller中注入service的时候使用@Autowired自动注入,@Qualifier(“beanId”)来指定注入哪一个。
Controller中注入service的时候使用@Resource(type = 类名.class)来指定注入哪一个。
每个service的impl都可以指定名称(使用@Service(“名称”)) Controller中注入service的时候使用名称来指定注入哪一个(使用@Resource(name=“名称”))。 @Service注解,其实做了两件事情: 1、声明TeacherServiceImpl.java是一个bean。因为TeacherServiceImpl .java是一个bean,其他的类才可以使用@Autowired将TeacherServiceImpl 作为一个成员变量自动注入。
2、TeacherServiceImpl.java在bean中的id是"teacherServiceImpl ",即类名且首字母小写。
注意:不能有同名的,不然要报错。
@Autowired注解的意思就是: 当Spring发现@Autowired注解时,将自动在代码上下文中找到和其匹配(默认是类型匹配)的Bean,并自动注入到相应的地方去。
@Resource的作用相当于@Autowired。
1.@Autowired是Spring的注解,@Resource是J2EE的注解,这个看一下导入注解的时候这两个注解的包名就一清二楚了。
2.@Autowired默认按照byType方式进行bean匹配,@Resource默认按照byName方式进行bean匹配。
3.@Autowired默认情况下必须要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false)。
方法一代码如下: 接口
public interface HumanService {
public String name();
}
接口实现类
@Servicepublic class TeacherServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("teacher");
return "teacher";
}
}
@Servicepublic class DoctorServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("doctor");
return "doctor";
}
}
控制器
@RestController
public class HumanController {
// @Resource(type = DoctorServiceImpl.class) //方法二
@Autowired
@Qualifier("teacherServiceImpl")
private HumanService humanService;
@RequestMapping("/name")
public String name(){
return humanService.name();
}
}
方法三代码如下: 接口
public interface HumanService {
public String name();
}
接口实现类
@Service("teacherService")
public class TeacherServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("teacher");
return "teacher";
}
}
@Service("doctorService")
public class DoctorServiceImpl implements HumanService {
@Override
public String name() {
System.out.println("doctor");
return "doctor";
}
}
控制器
@RestController
public class HumanController {
@Resource(name="doctorService")
private HumanService humanService;
@RequestMapping("/name")
public String name(){
return humanService.name();
}
}
@Qualifier
中引用。@Qualifier
,Spring可能会在多个实现类中选择一个默认的,这可能不是我们期望的结果。在Spring应用中,当一个Service接口有多个实现类时,使用@Qualifier
注解可以帮助我们明确地注入所需的实现类,从而更好地管理不同业务逻辑的组件。
大功告成~ 求一波关注?收藏~