Spring Component依赖注入具有多个实现的字段

时间:2015-12-01 11:38:54

标签: java spring spring-mvc dependency-injection

我有一个MyMessageConsumer类,它是一个spring组件。我有自动连接的MessageReceiver接口,如下所示:

    @Component
    @Scope("prototype")
    public class MyMessageConsumer {

     @Autowired
     private MessageReceiver messageReceiver;

    }

我想创建MyMessageConsumer的多个bean实例,每个实例都有MessageReceiver的不同实现,比如TextMessageReceiver,XMLMessageReceiver,JSONMessageReceiver。

    // If a setter is provided in MyMessageConsumer, then it would be suffiecent. But how to do it without setter.

在上述场景中,是否可以在没有setter方法的情况下注入不同的实现?否则请提出最佳选择。

提前致谢。

1 个答案:

答案 0 :(得分:0)

一个选项是删除MyMessageConsumer中的@autowired。

@Component
@Scope("prototype")
public class MyMessageConsumer {

    private MessageReceiver messageReceiver;

    public MessageReceiver getMessageReceiver() {
        return messageReceiver;
    }

    public void setMessageReceiver(MessageReceiver messageReceiver) {
        this.messageReceiver = messageReceiver;
    }
}

然后定义MessageReceiver bean

@Bean
public TextMessageReceiver textMessageReceiver() {
    return new TextMessageReceiver();
}

@Bean
public XMLMessageReceiver xMLMessageReceiver() {
    return new XMLMessageReceiver();
}

然后你需要定义你的MessageConsumers

@Bean
@Autowired
public MyMessageConsumer myMessageConsumer1(TextMessageReceiver textMessageReceiver) {
    MyMessageConsumer m = new MyMessageConsumer();
    m.setMessageReceiver(textMessageReceiver);
    return m;
}

@Bean
@Autowired
public MyMessageConsumer myMessageConsumer2(XMLMessageReceiver xMLMessageReceiver) {
    MyMessageConsumer m = new MyMessageConsumer();
    m.setMessageReceiver(xMLMessageReceiver);
    return m;
}