Spring-同个接口注入多个实例

一般开发,都是一个接口对应一个实现类,但是有时候有些业务场景可能面临一个接口对应多个实现类,这个时候如果直接使用@Autowire注入有可能就会报错,下面就把常用解决方法阐述一下:比如下面这个服务接口,就有多个实现

//生产消息服务接口
public interface IProducerService {}

//使用kafak发送消息
@Service("kafkaProducerService")
@Log4j2
public class KafkaProducerService  implements IProducerService {}

//使用rabbitmq发送消息
@Service("rabbitProducerService")
@Log4j2
public class RabbitProducerService implements IProducerService {}

//使用rocketmq发送消息
@Service("rocketProducerService")
@Log4j2
public class RocketProducerService implements IProducerService {}



我们可以通过如下三种注入方式,完成多接口的实例注入

1 使用@Autowired:service对象名要和beanName相同

    @Autowired
    private IProducerService kafkaProducerService;

    @Autowired
    private IProducerService rocketProducerService;

    @Autowired
    private IProducerService rabbitProducerService;

2 使用 @Resource:注入的name的名称要和service的对象名要一致

    @Resource(name = "kafkaProducerService")
    private IProducerService kafkaProducerService;

    @Resource(name = "rocketProducerService")
    private IProducerService rocketProducerService;

    @Resource(name = "rabbitProducerService")
    private IProducerService rabbitProducerService;

3 使用 @Autowired + @Qualifier


    @Qualifier(value = "kafkaProducerService")
    @Autowired
    private IProducerService getKafkaProducerService;

    @Qualifier(value = "rocketProducerService")
    @Autowired
    private IProducerService getRocketProducerService;

    @Qualifier(value = "rabbitProducerService")
    @Autowired
    private IProducerService getRabbitProducerService;

下一次会介绍如何通过条件进行动态匹配实例的创建

你可能感兴趣的:(接口与多实现类匹配)