jax-rsjersey-2.0spring-jersey

Jersey 2 and Spring Boot - Not able to inject using @Context on Provider


Using Jersey 2.3 on Spring Boot 2.4. I have 2 JAX-RS providers. One of them implements ContainerRequestFilter(PreMatching) and another one extends JacksonJaxbJsonProvider(from jackson-jaxrs-json-provider).

I am setting a property in ContainerRequestFilter onto ContainerRequestContext. Then I am trying to inject ContainerRequestContext onto another JAX-RS Provider using @Context. But this injection is always coming null.

If I inject same object onto a JAX-RS resource using @Context, Jersey does inject it. Not sure what I am missing here. Any help is greatly appretiated.

@PreMatching
@Provider
public class MyJaxRSContextProvider implements ContainerRequestFilter {

    @Context
    Providers providers;

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        requestContext.setProperty("myProperty", property);
    }
}

@Provider
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.WILDCARD)
public class MyJsonJaxRSProvider extends JacksonJaxbJsonProvider {

    @Context
    ContainerRequestContext requestContext;

    @Override
    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
        return true;
    }

    @Override
    public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
      //requestcontext is always null
      requestContext.getProperty("myProperty");
    }
}

Solution

  • Things to consider: