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

编程入门 行业动态 更新时间:2024-10-27 06:27:39
本文介绍了使用泛型通过上下文获取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

本文发布于:2023-11-23 02:21:04,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   spring   bean

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!