【问题标题】:Spring autowired collection of qualified beansSpring 自动装配合格 bean 的集合
【发布时间】:2017-04-29 00:04:47
【问题描述】:

我有一些带有 @Qualifier 注释的 Spring @Components,假设它在示例“A”和“B”中。我想将它们(仅使用注释)注入到列表中。我该怎么做?

@Component
public class WhatIHave {

    @Autowired
    @Qualifier("A")
    private MyType firstBean;

    @Autowired
    @Qualifier("B")
    private MyType secondBean;
    ....
}

@Component
public class WhatIWantToHave {

    @Autowired
    @Qualifier("A", "B") //something like that
    private List<MyType> beans;
    ...
}

我需要在@Configuration 类中进行吗?

@Configuration
public class MyConfiguration {

    @Autowired
    @Qualifier("A")
    private MyType firstBean;

    @Autowired
    @Qualifier("B")
    private MyType secondBean;

    @Bean
    public List<MyType> beans() {
        return Lists.newArrayList(firstBean, secondBean);
    }
}

或者还有其他方法可以做到这一点?

【问题讨论】:

  • 只需从@Autowired 列表中删除@Qualifier
  • 我知道 @Qualifier("A", "B") 语法不正确,但这只是我正在寻找的一个想法,而不是我提供的配置类。
  • 寻找这个answer

标签: java spring collections dependency-injection autowired


【解决方案1】:
@Autowired
@Qualifier("A")
private MyType firstBean;

@Autowired
@Qualifier("B")
private MyType secondBean;

然后:

List<MyType> list = new ArrayList<>();
list.add(firstBean);
list.add(secondBean);

【讨论】:

  • 这很有效,但不是很好的解决方案,因为需要向类添加新字段。我认为向@Configuration 类添加新字段更好。但我想知道这种唯一基于注释的解决方案。
【解决方案2】:

这个解决方法怎么样

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class TypeCollector implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;
    }

    public <T> List<T> getBeans(Class<T> clazz, String... names) {
        List<T> list = new ArrayList<>();
        for (String name : names) {
            list.add(applicationContext.getBean(name, clazz));
        }
        return list;
    }
}

您可以自动装配 TypeCollector 并请求 bean 运行时。缺点是运行时会得到 NoSuchBeanDefinitionException,并且必须使用 bean 名称而不是限定符。

【讨论】:

  • 在我看来,代码比@Configuration 类多得多
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
  • 2015-05-07
  • 2016-10-21
  • 2020-02-12
  • 2020-03-04
  • 2016-09-27
相关资源
最近更新 更多