我有一堆实现类型 Repository<T ? extends Node>
的存储库 bean .现在我可以从用户那里得到一个随机节点列表,我想为每个节点获得适当的存储库。自 Spring 4.0RC1我们可以像这样 Autowiring 存储库:
@Autowired Repository<SomeNode> someNodeRepository;
记录在案here .
这很好用,但我的问题是如何根据通用类型动态地执行此操作。
我想做的是:
public <T extends Node> T saveNode(T node) {
Repository<T> repository = ctx.getBean(Repository.class, node.getClass());
return repository.save(node);
}
其中第二个参数是泛型类型。 这当然行不通,尽管它可以编译。
我找不到关于此的任何/文档。
最佳答案
你可以这样做:
String[] beanNamesForType = ctx.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class, node.getClass()));
// If you expect several beans of the same generic type then extract them as you wish. Otherwise, just take the first
Repository<T> repository = (Repository<T>) ctx.getBean(beanNamesForType[0]);
关于java - 使用泛型通过上下文获取 spring bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30374267/