-
Notifications
You must be signed in to change notification settings - Fork 38.5k
Inconsistency between field and constructor injection #32493
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
It's not about field or constructor injection, but about |
I'm not sure I understand you fully, for field injection it's exactly what I expected throwing exception, but for constructor injection it should not inject empty list since I didn't put @SpringJUnitConfig
@ContextConfiguration(classes = ConstructorInjectTests.class)
@ComponentScan
public class ConstructorInjectTests {
@Autowired
Service service;
@Test
void test() {
}
@Component
public static class Service {
public Service(List<String> strings) {
}
}
} The test should throw exception but not. |
As of 5.1, this is intentional for such single-constructor (or equivalent factory method) scenarios as far as we would not be able to construct the bean at all otherwise: see #19901. Since constructors are not commonly annotated for dependency injection purposes, we have no strict notion of For field and method injection, we back out of such methods if an argument is not resolvable since it is fine to simply skip such injections points. Whereas for constructors and factory methods with their showstopper characteristics (and potential overloading etc.) we always had a different algorithm in place that got refined in 5.1 there. |
Would it be better inject empty list/set/map for field injection? BTW, Does it documented somewhere? I didn't find anything related in https://docs.spring.io/spring-framework/reference/core/beans/dependencies/factory-collaborators.html#beans-constructor-injection |
I'm not sure it's a feature or bug, test against 6.1.4.
Field injection:
Exception is thrown as expected:
Constructor injection:
Empty List is injected instead of throwing exception.
Factory method injection:
Empty List is injected instead of throwing exception.
The text was updated successfully, but these errors were encountered: