当前位置 博文首页 > 文章内容

    一个接口多个实现类,controller层如何操作

    作者: 栏目:未分类 时间:2020-10-06 15:00:19

    本站于2023年9月4日。收到“大连君*****咨询有限公司”通知
    说我们IIS7站长博客,有一篇博文用了他们的图片。
    要求我们给他们一张图片6000元。要不然法院告我们

    为避免不必要的麻烦,IIS7站长博客,全站内容图片下架、并积极应诉
    博文内容全部不再显示,请需要相关资讯的站长朋友到必应搜索。谢谢!

    另祝:版权碰瓷诈骗团伙,早日弃暗投明。

    相关新闻:借版权之名、行诈骗之实,周某因犯诈骗罪被判处有期徒刑十一年六个月

    叹!百花齐放的时代,渐行渐远!



    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; //正常启动