@Autowired 和 @Resource注解, 一个接口有多个实现类的时候Spring注入遇到的问题

先说下我遇到的问题,有一个接口 CompensationService, 有两个实现类 MusicCompensationStrategyImpl  和  TakeDeliveryCompensationStrategyImpl

在另一个类中需要用到其中的两个实现类,我直接CompensationService  com = new  MusicCompensationStrategyImpl () , 然后调用此实现类实现的方法,但是这个实现类注入了一个接口(此接口是一个@FeginClients接口,调用另一个服务),所以就出现了空指针异常,此接口注入不进来。

问题的原因是,我new个对象只是在JVM堆中产生了个对象,而Fegin是交给了Spring容器来管理,虽然此spring容器也是在JVM中,但是毕竟是两个不同的容器,如同两堵墙不能想通,果断弃之。

如下图 和 代码:

《@Autowired 和 @Resource注解, 一个接口有多个实现类的时候Spring注入遇到的问题》

 

@Slf4j
@Service(value = "takeDeliveryCompensationStrategyImpl")
public class TakeDeliveryCompensationStrategyImpl implements CompensationService {

    @Autowired
    private TakeDeliveryServiceOrderService takeDeliveryServiceOrderService;

    @Override
    public Result<String> compensationMethod(OrderForm orderForm, Long accountId) {
        Result<String> takeDeliveryServiceOrder = takeDeliveryServiceOrderService.createTakeDeliveryServiceOrder(orderForm);
        return takeDeliveryServiceOrder;
    }
}

 

如下:

@Slf4j
@Service("musicCompensationStrategyImpl")
@AllArgsConstructor
public class MusicCompensationStrategyImpl implements CompensationService {

    CompensationOrderService compensationOrderService;
    AccountRemoteService accountRemoteService;

    @Override
    public Result<String> compensationMethod(OrderForm orderForm, Long accountId) {

 

又用@Autowired注解,启动报错,信息显示无法不知该注入那个实现类,因为这个注解是按照类型来的,出现了两个实现类,也不知道按照那个, 果断弃之。

 

最后用@Resource注解,这个是按照name来的,在每个实现类上加上,如 @Service(“musicCompensationStrategyImpl”),类名全程(首字母小写, 看我上面的代码),然后在要调用的类注入  @Resource(name = “musicCompensationStrategyImpl”)

@Resource(name = "musicCompensationStrategyImpl")
private CompensationService compensationServiceMusic;
@Resource(name = "takeDeliveryCompensationStrategyImpl")
private CompensationService compensationServiceTake;

 

点赞