First, just reply to the comment in the accepts answer.
"What does the binding do? What if I have an interface and implementation?"
It just reads bind( implementation ).to( contract ) . You can use an alternative .in( scope ) chain. The default PerLookup . Therefore, if you want a singleton, you can
bind( implementation ).to( contract ).in( Singleton.class );
Also has RequestScoped
In addition, instead of bind(Class).to(Class) you can also bind(Instance).to(Class) , which will be automatically single.
Adding to accepted answer
For those who are trying to figure out how to register the AbstractBinder implementation in your web.xml (i.e. you are not using ResourceConfig ), it seems that the binder will not be detected through packet scanning, i.e.
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value> your.packages.to.scan </param-value> </init-param>
Or is it either
<init-param> <param-name>jersey.config.server.provider.classnames</param-name> <param-value> com.foo.YourBinderImpl </param-value> </init-param>
To make it work, I had to implement Feature :
import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; import javax.ws.rs.ext.Provider; @Provider public class Hk2Feature implements Feature { @Override public boolean configure(FeatureContext context) { context.register(new AppBinder()); return true; } }
The @Provider should allow Feature to be displayed when scanning a package. Or without scanning packages, you can explicitly register Feature in web.xml
<servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class> <init-param> <param-name>jersey.config.server.provider.classnames</param-name> <param-value> com.foo.Hk2Feature </param-value> </init-param> ... <load-on-startup>1</load-on-startup> </servlet>
See also:
and for general information from the jersey documentation
UPDATE
Factories
In addition to the main binding in the accepted answer, you also have factories where you can have more complex creation logic and also have access to the request context information. for example
public class MyServiceFactory implements Factory<MyService> { @Context private HttpHeaders headers; @Override public MyService provide() { return new MyService(headers.getHeaderString("X-Header")); } @Override public void dispose(MyService service) { } } register(new AbstractBinder() { @Override public void configure() { bindFactory(MyServiceFactory.class).to(MyService.class) .in(RequestScoped.class); } });
You can then introduce MyService into your resource class.