Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

I was implementing a custom entity provider in a Jersey REST service when I came across an error during deployment: "java.lang.IllegalStateException: Not inside a request scope." That struck me as a little odd since I was trying to inject a ContainerRequestContext into a MessageBodyWriter, which should have been within request scope. After some research and this Jersey issue I found a solution.

This is what I was trying to do in my class:
 MessageBodyWriter
@Context
ContainerRequestContext crc;


...which was throwing this exception...
 Exception
java.lang.IllegalStateException: Not inside a request scope."
weblogic.application.ModuleException: java.lang.IllegalStateException: Not inside a request scope.
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
...
Caused By: java.lang.IllegalStateException: Not inside a request scope.
at jersey.repackaged.com.google.common.base.Preconditions.checkState(Preconditions.java:173)
at org.glassfish.jersey.process.internal.RequestScope.current(RequestScope.java:233)
at org.glassfish.jersey.process.internal.RequestScope.findOrCreate(RequestScope.java:158)
at org.jvnet.hk2.internal.Utilities.createService(Utilities.java:2022)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:114)
at org.jvnet.hk2.internal.ServiceHandleImpl.getService(ServiceHandleImpl.java:88)
at org.glassfish.jersey.internal.inject.ContextInjectionResolver.resolve(ContextInjectionResolver.java:126)
...


The solution was to inject a ResourceContext instead and then look up the ContainerRequestContext when needed.

So my injection code became:
 MessageBodyWriter
@Context
ResourceContext resourceContext;


...and then to get the ContainerRequestContext I simply got it from the ResourceContext like so:
 MessageBodyWriter
ContainerRequestContext crc =
resourceContext.getResource(ContainerRequestContext.class);


This worked with Jersey 2.x (2.25.1 in my case).



-i

A quick disclaimer...

Although I put in a great effort into researching all the topics I cover, mistakes can happen. Use of any information from my blog posts should be at own risk and I do not hold any liability towards any information misuse or damages caused by following any of my posts.

All content and opinions expressed on this Blog are my own and do not represent the opinions of my employer (Oracle). Use of any information contained in this blog post/article is subject to this disclaimer.
Hi! You can search my blog here ⤵
NOTE: (2022) This Blog is no longer maintained and I will not be answering any emails or comments.

I am now focusing on Atari Gamer.