4

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>();
    }
}
1
  • 1
    instead of 'cars' variable, you could have taken 'questions'. :) Commented Mar 12, 2012 at 14:35

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

You can make like this

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

With is something like

public static interface Car
{
   String getName();
}

Comments

2

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"/>

Comments

-2

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;

1 Comment

@Autowire annotation as suggested above will throw an exception and we need to define the list in the applicationContext.xml file as mentioned in the link stackoverflow.com/questions/16784321/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.