最小,完整且可验证的示例
这是一个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: {}
如何将List
或Collection
注入@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
。
List<Long>
bean创建Long
,并将其收集起来。List<Long>
; Spring寻找单个Long
bean。@Qualifier
似乎没有帮助@Resource
不能在方法参数中使用。注意:此问题不与以下任何内容重复: