Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey: how to use InjectableProvider with @Context annotation?

I followed this post and created by first custom injectable provider, a LocaleProvider that scans the HTTP Request for the Accept-Language header. It works fine if I use it within a Jersey resource:

@Path("test")
@GET
public Response getStatus(@Context Locale locale) {
    log.finer("Locale: "+ locale);

    Response response = Response
            .noContent()
            .build();
    return response;
}

But when I want to use it in an ExceptionMapper I don't know how to inject the locale. I've tried to annotate it as a member variable:

public class MyExceptionMapper implements ExceptionMapper<MyException> {
  @Context
  private Locale locale;

  @Override
  public Response toResponse(MyException ex) {
    ...
  }
}

but this fails at deployment:

The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for field: private java.util.Locale com.package.MyExceptionMapper.locale

Other things like UriInfo or HttpServletRequest can be injected like that. How do I get access to my own LocaleProvider?

FYI this is on Glassfish 3.1.1 using Jersey 1.8.

like image 342
Hank Avatar asked Oct 03 '11 09:10

Hank


1 Answers

There is a scope mismatch. ExceptionMapper is a singleton, while your injectable is per-request-scope. UriInfo works around it using ThreadLocals.

like image 137
Martin Matula Avatar answered Nov 08 '22 08:11

Martin Matula