java - 使用泛型通过上下文获取 spring bean

标签 java spring generics

我有一堆实现类型 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/

相关文章:

java - 如何配置 Logback 以将记录器的不同级别记录到不同的目的地?

c# - 调用Web服务对象的方法

java - Keycloak - 是否可以在领域之间共享一组公共(public)用户?

spring - 在tomcat上实现 Spring 交易的最佳方式

java - 实例化类型参数的对象

java - 对这个泛型用例感到困惑

java - 最小平均两片可塑性

java - 为什么 Volley 返回空值?

java - Vaadin Spring (Vaadin 8) 未找到任何分页组件

java - 如何在java中开始使用泛型类型