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 toList<Long>
as needed - The other injects a
List<Long>
created by a method into the context. This version throwsNoSuchBeanDefinitionException: 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 anyLong
bean injected into the context, which it gathers up. - The manually created
List<Long>
is ignored; Spring looks for singleLong
beans. @Qualifier
doesn't seem to help@Resource
cannot be used in method arguments.
Note: This question is not a duplicate of any of: