[英]How to dynamically inject different implementation for the same Interface using spring
我有一个接口和该接口的两个实现
接口定义:
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放置。
要考虑的另一种选择是使用配置Bean-例如-
@Configuration
public class EntityRepositoryConfiguration {
private Map<Entity, EntityRepository> entityEntityRepositoryMap = new HashMap<>();
protected EntityRepositoryConfiguration() {
entityEntityRepositoryMap.put(Entity.Book, new BookRepository());
}
@Bean
public EntityRepository getByEntityType(Entity entity) {
return entityEntityRepositoryMap.get(entity);
}
}
然后将配置bean注入其他bean,并使用getEntityType方法(例如)来注入bean。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.