java - 如何使用spring动态注入(inject)同一接口(interface)的不同实现

标签 java spring

我有一个接口(interface)和该接口(interface)的两个实现

接口(interface)定义:

public interface DoSomething {}

两种实现:

public ImplementationOne implements DoSomething{}
public ImplementationTwo implements DoSomething{}

然后在另一个类中,我想根据条件获得不同的实现(ImplementationOne或ImplementationTwo),我该如何使用Spring来做到这一点?

类似于..

Public ServiceManager {
Private DoSomething doSomething = null;
Public void do() {
If (condition1) {
doSomething = new ImplementationOne();
} else {
doSomething = new ImplementationTwo();
}
}
}

最佳答案

您绝对应该使用 @Autowire 注释自动连接 ApplicationContext 类型。那么如果你这样做:

@Autowire
ApplicationContext context

然后你应该像这样得到你想要的bean:

context.getBean(yourDesiredType.class)

就像这样,您可以根据您的示例获取想要放置在任何匹配类型下的任何 bean。

关于java - 如何使用spring动态注入(inject)同一接口(interface)的不同实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43718461/

相关文章:

java - 如何使用 Spring MockMvc 放置多部分/表单数据?

spring - Spring feign 客户端中 @QueryParam 名称中的特殊字符

java - 如何在电子邮件正文中显示图像?

java - Android服务重启后不工作,给出ANR错误

java - 为什么JToolBar没有出现?

java - 一个接一个地打乱不超过两个相同类别元素的表

java - Spring 和 jackson (休息): Modify request body before reaching to controller : Add default values to properties if properties are not present in json rq

java - DJI P3 Advanced Mobile SDK 虚拟摇杆无法使用?

java - 禁用 Spring Boot Web 客户端日志

sql-server - Spring 批处理 : efficient way to query results of a stored procedure within a tasklet