Search code examples
jax-rscdiopen-liberty

Using constructor injection with CDI in OpenLiberty


I'm building a small Java EE 8 application that should run on OpenLiberty. It has a JAX-RS ContainerResponseFilter that looks like this:

package my.package;

import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;

@Provider
public class MyFilter implements ContainerResponseFilter {
    private final MyService myService;

    @Inject
    public DiagnosticsFilter(final MyService myService) {
        this.myService = myService;
    }

    @Override
    public void filter(final ContainerRequestContext request, final ContainerResponseContext response) {
        // Never mind this
    }
}

If I write the filter like this and start my app, the myService argument to the constructor is null. However, if field is annoted with @Inject and the constructor is omitted, the field is being injected correctly.

The MyService class is annotated with @Stateless, and in beans.xml I have set bean-discovery-mode="all".

Any idea what I'm doing wrong? Is this actually supposed to work? The Weld documentation suggests that it should, but I'm not sure it's in the CDI spec as well...


Solution

  • This is a long story...And some people are working to solve the problem: JAX-RS injection != CDI injection
    It shoud be solved in JAX-RS 2.2 ad CDI injection should be used in place of JAX-RS injection and JAX-RS v3.0 will totally remove the JAX-RS injection
    Read this on the subject:
    https://www.eclipse.org/community/eclipse_newsletter/2019/february/Jakarta_EE_9.php
    https://github.com/eclipse-ee4j/jaxrs-api/issues/569
    https://github.com/eclipse-ee4j/jaxrs-api/issues/639
    https://groups.google.com/forum/#!topic/microprofile/gvj94XBhtvM