spring中的数组依赖注入?

发布于 08-12 01:48 字数 496 浏览 8 评论 0原文

有没有办法使用依赖注入来注入 Spring 中特定接口的所有可用实现?

这与 针对 .NET 的要求是一样的

虽然我的目标是为此使用 @Autowired:

public class Foo{
  @Autowired
  private IDataCollector[] collectors;
}

这是否受支持,这是否需要黑客攻击,或者我应该最好使用另一个组件,其中 IDataCollector 的所有实现都自行注册并使用该访问器组件进行自动连接而不是数组注入?

我能想到为什么这可能不会默认实现的一个原因可能是,它还会在不合适的地方注入可能的模拟实现。尽管我仍然感兴趣这是否可能。 :)

is there a way to use dependency injection to inject all available implementations of a specific interface in spring?

This is kind of the same thing as asked here for .NET.

Though my aim is to use @Autowired for this:

public class Foo{
  @Autowired
  private IDataCollector[] collectors;
}

Is this supported, would this require hacking or should I preferably use another component where all implementations of IDataCollector register themselve and use that accessor component with autowired instead of the array injection?

A reason I can think of why this may not be implemented per default may be, that it would also inject possible mock implementations where inappropriate. Though I'm still interested wether this is possible or not. :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长安忆2024-08-19 01:48:57

您的示例应该可以正常工作,List 也应该可以正常工作。在询问之前您是否尝试过,但发现不起作用?

https://docs。 spring.io/spring/docs/current/spring-framework-reference/core.html#beans-autowired-annotation

也可以提供所有
特定类型的豆子
ApplicationContext 通过添加
字段或方法的注释
需要该类型的数组。

Your example should work fine, as should List<IDataCollector>. Did you give it a try before asking, and found it didn't work?

https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#beans-autowired-annotation

It is also possible to provide all
beans of a particular type from the
ApplicationContext by adding the
annotation to a field or method that
expects an array of that type.

给妤﹃绝世温柔2024-08-19 01:48:56

你可以注入一个列表,Spring 会为你转换它:

<util:list id="collectors">
  <value>[email protected]</value>
  <value>[email protected]</value>
</util:list>

you can inject a List and Spring will convert this for you:

<util:list id="collectors">
  <value>[email protected]</value>
  <value>[email protected]</value>
</util:list>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文