春季自动连线合格的豆类 [英] Spring autowired collection of qualified beans

查看:70
本文介绍了春季自动连线合格的豆类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些带有@Qualifier批注的Spring @Components,让我们说它在示例"A"和"B"中.我想将它们(仅使用批注)注入到List中.我该怎么办?

I have some Spring @Components with @Qualifier annotations, let's say it's in example "A" and "B". I want to inject them (using only annotations) into List. How can I do that ?

@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类中进行制作吗?

Do I need to make it in @Configuration class ?

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

还是有另一种方法?

推荐答案

此解决方法如何

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

The you can autowire the TypeCollector and ask for the beans runtime. The disadvantage is that you will get NoSuchBeanDefinitionException at runtime, and you have to use bean names instead of qualifier.

这篇关于春季自动连线合格的豆类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆