Spring should tolerate zero-argument constructors with javax.inject.Inject [SPR-15005] #19572
Comments
Juergen Hoeller commented I don't consider zero-arg Could you elaborate on your experience with other DI frameworks where there has to be at least one |
Greg Methvin commented Dagger requires you to add a default constructor with Guice also has an option to require |
Juergen Hoeller commented Alright, we'll align with that then and leniently accept annotated no-arg constructors as of 4.3.5! |
Greg Methvin commented Awesome. Thanks for the quick resolution! |
Greg Methvin opened SPR-15005 and commented
According to https://docs.oracle.com/javaee/6/api/javax/inject/Inject.html, "injectable constructors are annotated with
@Inject
and accept zero or more dependencies as arguments". However, when you try to use@Inject
with a zero-argument constructor, you receive an IllegalStateException: "Autowired annotation requires at least one argument".In other words,
@Autowired
requires at least one argument in the constructor, and@Inject
requires at least zero. Spring attempts to support the@Inject
annotation by treating it as equivalent to@Autowired
(see https://github.com/spring-projects/spring-framework/blob/v5.0.0.M3/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java#L149), but full support requires supporting zero-argument constructors as well.This makes it a bit more difficult if you'd like to create a library that supports multiple DI frameworks, many of which have (or at least allow you to configure) a requirement that injectable classes have at least one constructor annotated with
@Inject
.So, I guess there are a few options here:
@Inject
differently from@Autowired
when autowiring beans@Autowired
to require zero or more arguments like@Inject
(I'm not sure why this would be a bad thing).I'm not that familiar with Spring so perhaps one of these things is already possible. But it didn't seem evident to me looking at the code.
Affects: 4.3.4, 5.0 M3
Reference URL: https://github.com/spring-projects/spring-framework/blob/v5.0.0.M3/spring-beans/src/main/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessor.java#L149
Issue Links:
@Autowired
optional on a single constructor of a class decorated with@Component
@Autowired
constructors for configuration classesReferenced from: commits 8b5ee4e, 934fffe
The text was updated successfully, but these errors were encountered: