Initialize empty arraylists in Spring configuration?

I am learning Spring, and I am reading Spring in an action book. I wonder if you want to enter an empty arraylist (if possible) or create one, as in the example below?

public class StackOverflow { private List<Car> cars; public StackOverflow() { cars = new ArrayList<Car>(); } } 
+4
source share
4 answers

You can enter an empty list like this, however this is probably not necessary if you are not trying to set up an example spring XML config template, perhaps.

 <property name="cars"> <list></list> </property> 

If you want to quickly set empty lists to prevent null pointer issues, just use Collections.emptyList (). You can also do this inline as follows. Note that Collections.emptyList () returns an unmodifiable list.

 public class StackOverflow { private List<Car> cars = Collections.emptyList(); 

You will also need getters and setters for cars that can use it from spring XML.

+4
source

You can do this:

 <util:list id="emptyList" value-type="Cars"> </util:list> 

With something like

 public static interface Car { String getName(); } 
+1
source

I am having a problem with this answer . I think Spring complains when you open a collection, but don’t add any elements to it, as indicated in the example in this post. If this does not work, try the following. This worked for me for util:set .

 <util:list id="emptyList" value-type="Cars"/> 
+1
source

You can use autowiring to enter all types of cars that are driven by Spring if your class (in this case StackOverflow) is created through Spring:

 @Autowire private List<Car> cars; 
-1
source

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


All Articles