Spring实现一个接口多个实现自动注入

最近项目遇到了一个问题,Spring一个接口怎么多实现?方法有很多,总结了下,有两种方法:

1. @Primary注解指定一个主的实现,使用@Autowired就能实现自动注入

需要实现的接口

public interface HelloService {
    public BizPo sayHi(String id);
}

接口实现1

@Service
@Primary
public class HelloHangZhouServiceImpl implements HelloService {

    @Override
    public BizPo sayHi(String id) {
        System.out.println(list);
        if (id.equals("1")) {
            System.out.println("数据源1");
        } else if (id.equals("2")) {
            System.out.println("数据源2");
        }
        System.out.println("默认数据源");
        return new BizPo(id,"hangzhou");
    }
}

接口实现2

@Service
public class HelloGuangZhouServiceImpl implements HelloService {
    @Override
    public BizPo sayHi(String id) {
        return new BizPo(id,"guangzhou");
    }
}

Controller层

@RestController
public class HelloController {
	//这里会自动注入加了@Primary注解的那个接口实现类
    @Autowired
    private HelloService helloService;
    
    //自动注入实现了HelloService接口的实现类
    @Autowired
    private List<HelloService> list;
    
    @GetMapping("/{id}")
    public @ResponseBody BizPo getById(@PathVariable String id){
        System.out.println("id ==> "+id);
        BizPo b = helloService.sayHi(id);
        System.out.println(b);
        return b;
    }
}

想要拿到所有的接口实现类怎么办?可以通过下面这个方式。

	@Autowired
    private List<HelloService> list;

那么如果我想拿到某个指定的bean怎么办?看方法2

2. @Service(“XXXX”)命名实现的名称+@Qualifier(“helloGuangZhouService”)&&@Resource指定需要注入的bean。

接口

public interface HelloService {
    public BizPo sayHi(String id);
}

实现1

@Service("helloGuangZhouService")
public class HelloGuangZhouServiceImpl implements HelloService {
    @Override
    public BizPo sayHi(String id) {
        return new BizPo(id,"guangzhou");
    }
}

实现2

@Service("helloHangZhouService")
public class HelloHangZhouServiceImpl implements HelloService {

    @Override
    public BizPo sayHi(String id) {
        System.out.println(list);
        if (id.equals("1")) {
            System.out.println("数据源1");
        } else if (id.equals("2")) {
            System.out.println("数据源2");
        }
        System.out.println("默认数据源");
        return new BizPo(id,"hangzhou");
    }
}

controller


@RestController
public class HelloController {

    @Qualifier("helloGuangZhouService")
    @Resource
    private HelloService guangzhouservice;

    @Qualifier("helloHangZhouService")
    @Resource
    private HelloService hangzhouservice;
    
    @GetMapping("/{id}")
    public @ResponseBody BizPo getById(@PathVariable String id){
        System.out.println("id ==> "+id);
        BizPo b = guangzhouservice.sayHi(id);
        System.out.println(b);
        return b;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值