I want to use Constructor Injection, as it makes my unit tests safer and easier to write: I can't forget to set the fields to be injected. CDI supports that, and the javadoc of the @Inject
annotation says: "@Inject
is optional for public, no-argument constructors when no other constructors are present. This enables injectors to invoke default constructors."
I understand that other standards require a no-arg constructor (e.g. JAX-RS; see this question), which is a bummer. But even for a simple class like:
public class Bar {
private final Foo foo;
public Bar(Foo foo) {
this.foo = foo;
}
}
Weld fails, saying: DeploymentException: WELD-001408: Unsatisfied dependencies for type Bar
. When I add the @Inject
annotation, it works.
I really don't expect any bugs in Weld any more, as it's well established for years; I probably got something wrong. But maybe it slipped attention, just because the Jakarta EE community simply doesn't do any constructor injection.
This is not a Weld bug. As the specification indicates, you need @javax.inject.Inject
on your constructor. The only time you don't need it is when you have a zero-argument constructor and you do not wish for any other constructor to be called by the container.