I'm trying to create an ExceptionMapper with an abstract parent class and some injected fields. Here is the part of code, simplified:
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class MyExceptionMapper extends GenericExceptionMapper<MyException> {
@Override
public Response toResponse(MyException exception) {
...
}
}
public abstract class GenericExceptionMapper<T extends WebApplicationException> implements ExceptionMapper<T> {
@Inject
private ClassA fieldInParentA; // will be null.
@Inject
private ClassB fieldInParentB; // will be null.
// all kind of other stuff, including getters
...
}
ClassA and ClassB are simple classes with @Dependent, @ApplicationScoped or @Singleton scopes (tried all these).
The problem is, that the fields of the parent don't get injected (nor do I see any error report in logs) and the result of getFieldInParentA() or of getFieldInParentB() return null in toResponse(), although the problem is not with the injected objects (they gets injected properly in other places).
Further, to my biggest surprise, all of fieldInParentA, fieldInParentB and fieldInChild will be injected when also the child class contains injected field. This is so with any dependent, singleton or application scoped fields:
@Provider
@Produces(MediaType.APPLICATION_JSON)
public class MyExceptionMapper extends GenericExceptionMapper<MyException> {
@Inject
private ClassC fieldInChild; // **will be initialized!**
@Override
public Response toResponse(MyException exception) {
...
}
}
public abstract class GenericExceptionMapper<T extends WebApplicationException> implements ExceptionMapper<T> {
@Inject
private ClassA fieldInParentA; // **will be initialized!**
@Inject
private ClassB fieldInParentB; // **will be initialized!**
...
}
I might not understand properly the scopes (might it be the @Provider for blame?) or the inheritance of injected fields in Jakarta Dependency Injection, but besides not being able to initialize my classes (you might have guessed, that I don't want fields in the child class :) ) it is also bothering, that I do not understand this (apparently strange) behavior: how can the injection of a field in a parent depend on whether we there are fields in the child or not?! 1. I did a lot of search, but I unfortunately couldn't find anything useful.