如果一个接口有2个不同的实现, 那么怎么来指定的需要调用实现

在我们平时的系统开发中可能会一个接口有多是实现的情况存在,现在有两种实现方式

方式一:

@Autowired 配合 @Qualifier("类别名")一起使用

方式二:

使用@Resource(name = "类别名") 指定类的别名

测试代码

1. 接口


/**
 * 注入测试接口
 * @author: clx
 * @date: 2019/7/23
 * @version: 1.1.0
 */
public interface AutoTestService {
    String getString();
}

2。 实现

实现1

import com.example.javautilsproject.service.AutoTestService;
import org.springframework.stereotype.Service;

/**
 * 注入实现类 1
 * @author: clx
 * @date: 2019/7/23
 * @version: 1.1.0
 */
@Service("autoTestService1")
public class AutoTestService1Impl implements AutoTestService {
    @Override
    public String getString() {
        return "方式[1]调用成功";
    }
}

实现2


import com.example.javautilsproject.service.AutoTestService;
import org.springframework.stereotype.Service;

/**
 * @author: clx
 * @date: 2019/7/23
 * @version: 1.1.0
 */
@Service("autoTestService2")
public class AutoTestService2Impl implements AutoTestService {
    @Override
    public String getString() {
        return "方式[2]调用成功";
    }
}

3. 测试类


import com.example.javautilsproject.service.AutoTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: clx
 * @date: 2019/7/23
 * @version: 1.1.0
 */
@RestController
public class TestController {

    @Autowired
    @Qualifier("autoTestService1")
    private AutoTestService autoTestService1;

    @Autowired
    @Qualifier("autoTestService2")
    private AutoTestService autoTestService2;

    @Resource(name = "autoTestService1")
    private AutoTestService resourceAutoTestService1;

    @Resource(name = "autoTestService2")
    private AutoTestService resourceAutoTestService2;


    @GetMapping("autoTest")
    public void autoTest() {
        String autowired1 = autoTestService1.getString();
        String autowired2 = autoTestService2.getString();
        String resource1 = resourceAutoTestService1.getString();
        String resource2 = resourceAutoTestService2.getString();
        System.out.println("Qualifier----" + autowired1);
        System.out.println("Qualifier----" + autowired2);
        System.out.println("Resource----" + resource1);
        System.out.println("Resource----" + resource2);
    }
}

4. 测试结构

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值