使用泛型通过上下文获取spring bean [英] Get spring bean via context using generic

查看:94
本文介绍了使用泛型通过上下文获取spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆实现类型为 Repository< T的仓库bean?扩展Node> 。现在我可以从用户那里获得随机节点的列表,并且我想为每个节点获取适当的存储库。由于 Spring 4.0RC1 ,我们可以自动导入像这样的存储库:

  @Autowired存储库< SomeNode> someNodeRepository; 

如文件 here

工作正常,但我的问题是我如何可以根据泛型类型动态地做到这一点。



我想要做的是这样的:

  public< ; T扩展节点> T saveNode(T节点){
存储库< T> repository = ctx.getBean(Repository.class,node.getClass());
返回repository.save(node);
}

其中第二个参数是泛型类型。 这当然不起作用,尽管它编译了。



我找不到任何文档。

解决方案

您可以这样做:

  String [] beanNamesForType = ctx.getBeanNamesForType(ResolvableType.forClassWithGenerics(Repository.class,node.getClass())); 

//如果您希望有几个相同泛型类型的bean,可以根据需要提取它们。否则,只需取第一个
Repository< T> repository =(Repository< T>)ctx.getBean(beanNamesForType [0]);


I have a bunch of repository beans that implement type Repository<T ? extends Node>. Now I can get a list of random nodes from the user and I want to get the appropriate repository for each node. Since Spring 4.0RC1 we can autowire repositories like this:

@Autowired Repository<SomeNode> someNodeRepository;

As documented here.

This works fine, but my question is how I can do this dynamically based on the generic type.

What I want to do is something like:

public <T extends Node> T saveNode(T node) {
    Repository<T> repository = ctx.getBean(Repository.class, node.getClass());
    return repository.save(node);
}

Where the second parameter is the generic type. This of course does not work, although it compiles.

I can't find any/the documentation on this.

解决方案

You can do something like this:

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]);

这篇关于使用泛型通过上下文获取spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆