我有一个接口(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/