一个接口多个实现类,controller层如何操作
spring中controller层会注入 接口,然后通过接口调用方法。
如果一个接口对应一个实现类,这样操作没有问题,如果一个接口实现多个实现类(多态),这样操作就会出现问题。
解决方法:一个接口多个实现类,需注入指定的实现类
复制代码
例如:Interface 接口有两个实现类 InterfaceImpl1 和 InterfaceImpl2
//实现类1
@Service
public class InterfaceImpl1 implements Interface {
//实现类2
@Service
public class InterfaceImpl2implements Interface {
//业务类,controller
@Autowired Interface
private Interface interface;
按照上面的写法,启动服务时会报错
解决方法
1.指明实现类的优先级,注入的时候使用优先级高的实现类
//实现类1
@Service
@Primary //同一个接口的实现类,最多只能有一个添加该注解
public class InterfaceImpl1 implements Interface {
在controller中注入接口,默认使用的是Primary 标注的实现类的方法
2.通过 @Autowired 和 @Qualifier 配合注入
@Autowired
@Qualifier(“interfaceImpl1”)
Interface1 interface1; //正常启动
3.使用@Resource注入,根据默认类名区分
@Resource(name = “interfaceImpl1”)
Interface1 interface1; //正常启动
4.使用@Resource注入,根据@Service指定的名称区分
需要在实现类@Service后设置名称:
@Service(“s1”)
public class InterfaceImpl1 implements Interface {
@Resource(name = “s1”)
Interface1 interface1; //正常启动

浙公网安备 33010602011771号