Christoph Ellinger opened SPR-15897 and commented

I can autowire a list of beans like this:

@Autowired(required = false) List\ optionalBeanList;

If really no bean was supplied, optionalBeanList is now null. When I want to use this in my program later I have to include null checks.

I think it would be better to initialize an empty list.


Affects: 4.2.9

Comment From: spring-projects-issues

Juergen Hoeller commented

For a non-required case like this, we consider the entire injection point optional. This means that we are not even going to inject it if there are no actual depenencies found for it, leaving the injection point in its original state.

So for a field, we are not even going to set it, leaving it at its declared field initialization state which happens to be null in your case. You could simply initialize it with Collections.emptyList() to have a reliable non-null value in place, even if your object isn't managed by a DI container at all.

Comment From: spring-projects-issues

Christoph Ellinger commented

This is exactly what I did in that case.

I was just curious if my proposed behaviour would make sense.

Comment From: snicoll

I don't think so. The explicit flag of making it non required allows you to initialze the field differently if you wanted to. By initializing to an empty list, the container would force what the default value should be. Thanks anyway for the suggestion.