walsh walsh - 2 months ago 12
Java Question

How to @Autowired a List<Integer> in spring framework

I have a configuration class as below:

@Configuration
public class ListConfiguration {
@Bean
public List<Integer> list() {
List<Integer> ints = new ArrayList<>();
ints.add(1);
ints.add(2);
ints.add(3);
return ints;
}

@Bean
public int number() {
return 4;
}
}


I also have a test class as below

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = ListConfiguration.class)
public class ListTest {
@Autowired
List<Integer> ints;

@Test
public void print() {
System.out.println(ints.size());
System.out.println(ints);
}
}


But the output of the
print
method is
1
and
[4]
, why not
3
and
[1,2,3]
? Thank you very much for any help!

Answer

May be Spring is injecting all the Integer type beans into a List instead of Autowiring List<Integer> bean that you declared.

Probably if you add @Qualifier("list") at your injection point in your Test then it will provide the behavior you are expecting.