LuckyLuke
LuckyLuke

Reputation: 49097

Initialize empty arraylists in Spring configuration?

I am learning Spring and I read the Spring in Action book. I wonder if you are supposed to inject an empty arraylist (if that is possible) or create it like the example below?

public class StackOverflow {

    private List<Car> cars;

    public StackOverflow() {
        cars = new ArrayList<Car>();
    }
}

Upvotes: 4

Views: 15667

Answers (4)

burcakulug
burcakulug

Reputation: 627

I had a problem with this answer. I guess Spring complains when you open a collection, but don't add any items in it as given in the example in that post. If that doesn't work, try the one below. It worked for me for util:set.

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

Upvotes: 1

Omri Sivan
Omri Sivan

Reputation: 339

You can use autowiring to inject all Car types that are Spring managed, as long as your class (in this case StackOverflow) is instantiated via Spring:

@Autowire
private List<Car> cars;

Upvotes: -1

Richard Grossman
Richard Grossman

Reputation: 109

You can make like this

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

With is something like

public static interface Car
{
   String getName();
}

Upvotes: 2

Adam
Adam

Reputation: 36723

You can inject an empty list like this, however this is probably unnecessary, unless you're trying to setup an example template spring XML config perhaps.

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

If you want a quick way of setting empty lists to prevent null pointer problems, then just use Collections.emptyList(). You can also do it "inline' as follows. Note though that Collections.emptyList() returns an unmodifiable list.

public class StackOverflow {

    private List<Car> cars = Collections.emptyList();

You'll also need getters and setters for cars to be able to use it from spring XML.

Upvotes: 4

Related Questions