Cannot enter arrays list as dependency

I create a bean with annotations.

@Component public class MyClass { @Autowired private ArrayList<String> myFriends= new ArrayList<String>(); //Getters and setters } 

I get the following exception

Failed to create autowire field: private java.util.ArrayList com.mypackage.MyClass.myFriends; The nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: no bean match found for type [java.util.ArrayList] for the dependency: at least 1 bean is expected that qualifies as an auto-connect candidate for this dependency. Dependency Annotations: {@ org.springframework.beans.factory.annotation.Autowired (required = true)}

I also tried with this

 @Resource private ArrayList<String> myFriends= new ArrayList<String>(); 

I get the following exception

No bean mapping found for the type [java.util.ArrayList] found for the dependency: at least 1 bean is expected to qualify as an autwire candidate for this dependency. Dependency Annotations: {@ javax.annotation.Resource (shareable = true, mappedName =, description =, name =, type = class java.lang.Object, authenticationType = CONTAINER)}

Please let me know how to fix this.

0
source share
1 answer

In the XML file, you will need to define a list.

The util namespace is added to the XML file and add the following bean definition.

 <util:list id="myFriends"> <value>string1</value> <value>string2</value> <value>string3</value> </util:list> 

You need to change the type of the variable to List<String> instead of ArrayList<String> . This will facilitate implementation as well as improve coding practice. You need to add the โ€œQualifierโ€ annotation to indicate the bean identifier that should be entered; a qualifier may not be required if you have only one such list.

 @Component public class MyClass { @Autowired @Qualifier("myFriends") private List<String> myFriends= new ArrayList<String>(); //Getters and setters } 

Link to spring help documentation for util: list http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/xsd-config.html#xsd-config-body-schemas-util -list

+2
source

Source: https://habr.com/ru/post/1400952/


All Articles