我有一个接口和两个实现此接口
接口定义:
public interface DoSomething {}
两个实现:
public ImplementationOne implements DoSomething{}
public ImplementationTwo implements DoSomething{}
然后在另一个类中,我想根据条件获得不同的实现(实现方或实现(,我该如何使用Spring?
类似..
Public ServiceManager {
Private DoSomething doSomething = null;
Public void do() {
If (condition1) {
doSomething = new ImplementationOne();
} else {
doSomething = new ImplementationTwo();
}
}
}
您应该使用@Autowire注释肯定会自动使用电线应用程序类型。然后,如果您这样做:
@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);
}
}
然后将配置豆注入其他豆子,并使用getentityType方法(例如(将bean注入。