You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is tedious. We should be able to inject into records, it would be equivalent to constructor injection.
Currently the @Inject annotation has @Target({ METHOD, CONSTRUCTOR, FIELD }). I think if we add TYPE to that list, then the annotation would be allowed on records too and injection frameworks like dagger and spring can start supporting that. TYPE has been around since 1.5, so a Java version update would not be necessary.
The text was updated successfully, but these errors were encountered:
From CDI perspective (as a consumer of this annotation), just allowing to use it on types would cause ambiguity for other cases.
This is because a type may have arbitrary number of constructors and at most one at a time should have @Inject for container to know how to instantiate given class.
We would need to add some javadoc either explaining how this works with types in general or say that it's only taken into account for records.
CC @Ladicek
@h908714124 also, I assume this can be workarounded in your framework by declaring the compact constructor and annotating it? That should be a usage within bounds of current specification text.
record Heater(Logger logger) {
@Inject
public Heater {
}
void heat() {
// some code...
}
}
Yeah, annotating an empty compact constructor is the way to go here.
It is not very intuitive, because the constructor parameters are declared in the record header, but Java doesn't provide any syntax to annotate the record constructor without actually declaring the constructor. (Kotlin does, see e.g. https://kotlinlang.org/docs/annotations.html#usage, but it's not exactly pretty either in my opinion.)
The following is invalid:
To make it work, we have to convert the record to a class and annotate the constructor instead:
This is tedious. We should be able to inject into records, it would be equivalent to constructor injection.
Currently the
@Inject
annotation has@Target({ METHOD, CONSTRUCTOR, FIELD })
. I think if we addTYPE
to that list, then the annotation would be allowed on records too and injection frameworks like dagger and spring can start supporting that.TYPE
has been around since1.5
, so a Java version update would not be necessary.The text was updated successfully, but these errors were encountered: