java - jersey 2.x dependency injection -


hi facing problem while moving below code jersey 1.x jersey 2.x

@provider public class localeprovider       extends abstracthttpcontextinjectable<locale>       implements injectableprovider<context, type> {      @override     public injectable<e> getinjectable(componentcontext ic, context a, type c) {         if (c.equals(locale.class)) {             return this;         }          return null;     }      @override     public componentscope getscope() {         return componentscope.perrequest;     }      @override     public locale getvalue(httpcontext c) {         final locales locales = c.getrequest().getacceptablelanguages();         if (locales.isempty()) {           return locale.us;         }         return locales.get(0);     } } 

i understand hk2 available in jersey 2.0, cannot seem find docs jersey 2.0 integration.

if you're going use @context annotation, need implement factory<t> parameterized type want inject. can inject other standard injectable objects factory, instance httpservletrequest, containerrequestcontext, httpheaders among others. example, match what's going on in example above

import java.util.list; import java.util.locale; import javax.inject.inject; import javax.ws.rs.core.httpheaders; import org.glassfish.hk2.api.factory;  public class localefactory implements factory<locale> {      private final httpheaders headers;      @inject     public localefactory(httpheaders headers) {         this.headers = headers;     }      @override     public locale provide() {         list<locale> acceptablelanguges = headers.getacceptablelanguages();          if (acceptablelanguges.isempty()) {             return locale.us;         }          if ("*".equals(acceptablelanguges.get(0).tostring())) {             return locale.us;         }          return acceptablelanguges.get(0);     }      @override     public void dispose(locale t) { /* nothing */ } } 

then need bind factory. example in resourceconfig. can set scope there, in getscope() in example. there support singleton, requestscoped , perlookup (which default if not specified)

@applicationpath("/api") public class appconfig extends resourceconfig {      public appconfig() {         packages("packages.to.scan");          register(new abstractbinder(){             @override             public void configure() {                 bindfactory(localefactory.class).to(locale.class)                                          .in(requestscoped.class);             }         });     } } 

if using web.xml, can create feature , register abstractbinder there, seen here

after this, can inject

@get public response getlocale(@context locale locale) { 

if want use custom annotation, need implement injectionresolver custom annotation. can see complete example here, , read more in jersey documentation - defining custom injection annotation


Comments