gpt4 book ai didi

java - Spring组件对一个字段的多个实现的依赖注入(inject)

转载 作者:太空宇宙 更新时间:2023-11-04 13:10:28 25 4
gpt4 key购买 nike

我有一个 MyMessageConsumer 类,它是一个 spring 组件。我有 Autowiring 的 MessageReceiver 接口(interface),如下所示:

    @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 方法的情况下注入(inject)不同的实现?否则请建议最佳替代方案。

提前致谢。

最佳答案

一个选项是删除 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;
}

关于java - Spring组件对一个字段的多个实现的依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34019524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com