将集合注入@Configuration类的@Bean方法(Spring)

时间:2017-03-06 16:59:06

标签: java spring dependency-injection configuration

最小,完整且可验证的示例

这是一个Spring @Configuration类,以及它的测试类。

有两个版本,具体取决于已注释掉的部分:

  • 一个版本在上下文中注入Long,Spring会根据需要自动转换为List<Long>
  • 另一个将方法创建的List<Long>注入上下文。此版本会抛出NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Long] found for dependency [collection of java.lang.Long]: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}

如何将ListCollection注入@Bean方法?

@Configuration
public class TestConfig {

    //@Bean
    //public Long theLong() {
        //return 42L;
    //}

    @Bean
    public List<Long> theList() { //Long theLong) {
        List<Long> list = new ArrayList<>();
        list.add(42L);  // theLong);
        return list;
    }

    @Bean
    public Random random(
            List<Long> list) { // How to inject this?
            //Long theLong) {
        return new Random(list.get(0));
        //return new Random(theLong);
    }
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=TestConfig.class)
public class TestConfigTest {

    @Autowired
    private Random random;

    @Test
    public void test() {
        Assert.assertEquals(-1170105035, random.nextInt());
    }
}

原因在Auto-wiring a List using util schema gives NoSuchBeanDefinitionException 的已接受答案中给出,但此解决方案无法使用,因为无法使用@Resource

  • Spring尝试使用注入上下文的任何List<Long> bean创建Long,并将其收集起来。
  • 忽略手动创建的List<Long>; Spring寻找单个Long bean。
  • @Qualifier似乎没有帮助
  • @Resource不能在方法参数中使用。

注意:此问题不与以下任何内容重复:

0 个答案:

没有答案