2

I have searched everywhere for a basic example of how to use HK2 dependency injection in Jersey 2.0, but have come up short.

From this question, it appears you need to create a class which extends AbstractBinder. However, the rest of the example shows how to register the binder with your application by editing the web.xml file. However, I want to avoid this and would like to instead register the binder with my HttpServer instance directly.

This is what I have written for my HttpServer:

int port = config.getInt("port", 8080);
boolean useFake = config.getBoolean("fake", false);

final URI baseUri = URI.create("http://" + "localhost" + ":" + port + "/");
List<Binder> binders = Arrays.asList((Binder)new StatusModule(useFake),
    (Binder)new NetworkModule(useFake));
final ApplicationHandler applicationHandler = new ApplicationHandler();
applicationHandler.registerAdditionalBinders(binders);

WebappContext webappContext = new WebappContext("Webapp context", "/resources");

HttpServer server = GrizzlyHttpServerFactory.createHttpServer(
    baseUri, applicationHandler);
for(NetworkListener listener : server.getListeners()){
    listener.setCompression("on");
}
server.getServerConfiguration().addHttpHandler(
    new StaticHttpHandler("/jersey2app/www"), "/static");

Any help will be greatly appreciated.

Community
  • 1
  • 1
Danny Andrews
  • 456
  • 4
  • 10

1 Answers1

4

Turns out I just needed to add a couple of lines of code, but I'll post it here in case anyone else has the same problem.

ResourceConfig rc = new ResourceConfig();
rc.packages("com.danny.resources");
rc.registerInstances(new StatusModule(useFake), new NetworkModule(useFake));
GrizzlyHttpContainer resourceConfigContainer = ContainerFactory
    .createContainer(GrizzlyHttpContainer.class, rc);
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(baseUri);
server.getServerConfiguration().addHttpHandler(resourceConfigContainer, "/");

The ResourceConfig lets you tell the server where to find your dynamic resources, in my case "com.danny.resources". It also allows you to register hk2 binders which will be used to inject those resources into your code.

Hope this helps someone along the way, and I hope hk2/Jersey 2.0 puts out some more examples!

Danny Andrews
  • 456
  • 4
  • 10