Dependency Injection - pford68/jersey-city GitHub Wiki
Steps
-
Create a subclass of AbstractBinder and override its
configure()
method. -
In
configure()
, you'll map impls to interfaces as shown below:@Override public void configure() { bind(TodoDaoImpl.class).to(TodoDao.class); }
-
Then in another class you can inject the TodoDaoImpl into a TodoDao reference:
@Path("/todo") public class TodoResource { @Inject TodoDao dao; @GET @Produces({ MediaType.APPLICATION_JSON }) public Todo test() { return dao.getOne(); } }
Use JSR-330 annotations (e.g., javax.inject.Inject) for the injection.
@Context
When deploying a JAX-RS application using servlet then ServletConfig, ServletContext, HttpServletRequest and HttpServletResponse are available using @Context.
References
- http://blog.denevell.org/java-jersey-dependency-injection.html (very helpful)
- http://stackoverflow.com/questions/16216759/dependency-injection-with-jersey-2-0/29275727#29275727
- http://stackoverflow.com/questions/30116859/jersey-2-x-dependency-injection
- http://stackoverflow.com/questions/30116859/jersey-2-x-dependency-injection
- http://www.justinleegrant.com/?p=516
- https://hk2.java.net/inhabitant-generator.html
- https://jersey.java.net/documentation/latest/index.html (@Context)