Like @Autowired List <Integer> in spring
I have a configuration class as shown 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 shown 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 method of exit printis 1, and [4], why not 3, and [1,2,3]? Thank you so much for any help!
+4
2 answers
You have a bean type Integerand a bean type List<Integer>in the context of your application.
, bean, autowire, List<Integer>, . , Spring , AutowiredAnnotationBeanPostProcessor.
TL; DR , Spring :
@Value- beans .
- beans, .
, autwiring, List<Integer> Spring Integer beans , List<Integer> bean.
DefaultListableBeanFactory.
:
public Object doResolveDependency(DependencyDescriptor descriptor, String beanName,
Set<String> autowiredBeanNames, TypeConverter typeConverter) throws BeansException {
Class<?> type = descriptor.getDependencyType();
//Searches for an @Value annotation and
Object value = getAutowireCandidateResolver().getSuggestedValue(descriptor);
if (value != null) {
//Handle finding, building and returning default value
}
/*
* Check for multiple beans of given type. Because a bean is returned here,
* Spring autowires the Integer bean instance.
*/
Object multipleBeans = resolveMultipleBeans(descriptor, beanName, autowiredBeanNames, typeConverter);
if (multipleBeans != null) {
return multipleBeans;
}
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
Map<String, Object> matchingBeans = findAutowireCandidates(beanName, type, descriptor);
// Do more stuff here to try and narrow down to a single instance to autowire.
}
}
, , @Qualifer , beans .
EDIT:
, . bean . - @Value , Spring .
:
application.properties
list=1,2,3,4
bean:
@Bean
public ConversionService conversionService() {
return new DefaultConversionService();
}
, , , .
:
@Value("${list}")
private List<Integer> anotherList;
anotherList 1,2,3 4 .
+9