【问题标题】:Inject using spring lots of beans instances in a map/list without xml configuration在没有xml配置的地图/列表中使用spring注入大量bean实例
【发布时间】:2019-03-19 12:26:21
【问题描述】:

我怎样才能注入 java bean 的 Map(或 List),使用 spring 但不使用 xml 配置的一些不同类的实例(我们应该只使用注释)?我希望能够通过名称或实现类指定要注入该映射的特定实例

实例将使用以下方式声明:

@Component ("instanceA") 公共类 A 实现 I {
...
}

PS 为了简单起见,我们可以先假设所有实例都实现相同的接口,但这并不总是正确的......

【问题讨论】:

  • 您的问题似乎不完整,您能否添加更多信息,例如您希望在什么条件下选择您的豆类。此外,如果您希望将 bean 添加到列表中,它们必须实现相同的接口,否则映射必须是 Object 类型。
  • 没有选择bean的一般条件,我希望能够根据名称或实现类的名称来挑选每个特定的实例。它们都将实现相同的接口(这是通常的用法)

标签: java spring dependency-injection


【解决方案1】:

您可以使用 bean 工厂来访问所有必要的 bean

@Autowired
private ListableBeanFactory beanFactory;

beansOfType.getBeansOfType() 返回一个地图BeanName -> Bean

您只需要知道要“注入”的 bean 名称。 列出必要的BeanNames;

那么你可以只吃必要的豆子。

Map<String, YourInterface> beansOfType = beanFactory.getBeansOfType(YourInterface.class);

List<YourInterface> necessaryBeanNames.stream().map(b-> beansOfType.get(b)).filter(b -> b != null).collect(toList());

【讨论】:

  • 我想挑选实例而不是全部选择
  • @Qualifier 会帮助你吗?
  • 我更喜欢通过实现类而不是名称来加载 bean,因为它是静态类型的。
  • 你是对的,但是getBeansOfType() 为你提供了所有实现该类型的bean。你将如何过滤它们?
【解决方案2】:

目前还没有可以为您执行此操作的注释,但您可以使用 @Bean 和 @Qualifier 来获得所需的结果。

@Bean
public List<YourInterface> getList(@Qualifier("yourCherryPickedInterfaceImpl1") YourInterface yourCherryPickedInterfaceImpl1, @Qualifier("yourCherryPickedInterfaceImpl2") YourInterface yourCherryPickedInterfaceImpl2) {
    return Arrays.asList(new YourInterface[]{yourCherryPickedInterfaceImpl1, yourCherryPickedInterfaceImpl2});
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-07
    • 2015-09-20
    • 2013-05-24
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多