• 一个接口多个实现类,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; //正常启动
  • 相关阅读:
    python线程同步
    闭包、装饰器
    python中的return返回值
    常用内建函数
    python迭代器与生成器
    python基础之数据类型
    VS生成解决方案时报错: Your project does not reference ".NETFramework,Version=v4.5"
    Unity 低版本打开高版本项目
    关闭应用程序的所有子窗体
    按钮接收 Enter 键
  • 原文地址:https://www.cnblogs.com/jingpeng77/p/13773423.html
Copyright © 2020-2023  润新知