Spring自动装配合格的bean

时间:2016-12-13 19:49:16

标签: java spring collections dependency-injection autowired

我有一些带有@Qualifier注释的Spring @Components,让我们在例子中说出它" A"和" B"。我想将它们(仅使用注释)注入List。我怎么能这样做?

@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);
    }
}

还是有另一种方法可以做到这一点?

2 个答案:

答案 0 :(得分:0)

@Qualifier是知道在相同类型bean的情况下哪个bean有资格在字段上自动装配,为什么不呢:

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

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

然后:

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

答案 1 :(得分:0)

这个解决方法怎么样

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名称而不是限定符。