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");
}
}
Things to consider:
In some cases, if you register the provider as an instance, then injection may not occur. Best thing to do is to register the provider as a class or just use scanning provided by Jersey.
Some injectables are not proxiable, which will prevent smaller scoped services to be injected into larger scoped serviced (example: request scoped object into a a singleton). In this case, you should wrap the injection in javax.inject.Provider
@Inject
private javax.inject.Provider<ContainerRequest> requestProvider;
...
ContainerRequest request = requestProvider.get();