0

Minimal, Complete, and Verifiable Example

Here is a Spring @Configuration class, and a test class for it.

There are 2 versions, depending on commented-out sections:

  • One version injects a Long into the context, which Spring automatically converts to List<Long> as needed
  • The other injects a List<Long> created by a method into the context. This version throws 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: {}

How do you inject a List or Collection into an @Bean method?


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

The reason is given in the accepted answer to Auto-wiring a List using util schema gives NoSuchBeanDefinitionException but that solution is not usable here because @Resource cannot be used.

  • Spring tries to create a List<Long> using any Long bean injected into the context, which it gathers up.
  • The manually created List<Long> is ignored; Spring looks for single Long beans.
  • @Qualifier doesn't seem to help
  • @Resource cannot be used in method arguments.

Note: This question is not a duplicate of any of:

Community
  • 1
  • 1
Stewart
  • 17,616
  • 8
  • 52
  • 80

0 Answers0