Spring 3.2 annotation autowiring with multiple constructors

dsplynm picture dsplynm · Jul 13, 2014 · Viewed 14.4k times · Source

Spring docs:

Only one annotated constructor per-class can be marked as required, but multiple non-required constructors can be annotated.

If I have one autowired constructor, all is fine. If I have two or more autowired, but required=false annotated constructors, all is fine. But if I mix them in a way, such that there is one or more required=false constructor autowiring annotations and exactly one with the required=true, it throws an exception.

org.springframework.beans.factory.BeanCreationException: Invalid autowire-marked constructor: public annotationconfig.SomeBean(annotationconfig.AnotherBean). Found another constructor with 'required' Autowired annotation: public annotationconfig.SomeBean(annotationconfig.AnotherBean,annotationconfig.AnotherBean[])

Is this expected behavior? Am I missing something about how Spring dependency injection works? If this is normal, why is this a problem for Spring, why can't it handle a setup like this?

Answer

mike_m picture mike_m · Jul 13, 2014

I think the reason for that behavior is that if one of the constructors have @Autowired(required=true) then it must be called (because it is required) and because only one constructor can be called per object instantiation then what is the point of having other constructors with @Autowired(required=false)?

They won't be autowired anyway, because one of the constructors is already required and must be called. They can still be called without using Autowired mechanism, but in that case @Autowired(required=false) annotation is unnecessary.