Skip to content

Instantly share code, notes, and snippets.

@jcfrank
Last active August 29, 2015 14:13
Show Gist options
  • Save jcfrank/0e0c2f020f37f9ec0901 to your computer and use it in GitHub Desktop.
Save jcfrank/0e0c2f020f37f9ec0901 to your computer and use it in GitHub Desktop.
HK2 is a dependency injection framework used in Jersey 2. This pice of code demonstrate how to add custom bindings.

HK2

Jersey 2 uses HK2 as dependency injection framework.
Although there are modules for integrating with Guice or Spring.
We can still just use HK2 to avoid using two frameworks for the same purposes.
Following snippets are two very basic sample for using HK2.

Sample

@Contract
public interface Parser {
    String parse();
}
@Service
public class JsonParser implements Parser {
    @Override
    public String parse() {
        return "json parsed!";
    }
}
ServiceLocator serviceLocator = ServiceLocatorUtilities.createAndPopulateServiceLocator();

//Get config service from service locator.
DynamicConfigurationService dcs = serviceLocator.getService(DynamicConfigurationService.class);
DynamicConfiguration config = dcs.createDynamicConfiguration();

//Set up bindings here. Bind Serivice (implementation) to Contract (interface)
config.bind(BuilderHelper.link(JsonParser.class).to(Parser.class).build());
config.bind(BuilderHelper.link(ParserUser.class).build());
config.commit();

Guice Bridge

If we still want to use Guice.
Include Guice Bridge dependency, and set up Jersey 2's ResourceConfig like this:

public class MyApplication extends ResourceConfig {

    //Notice that Inject is the one in javax package. Not google.
    @Inject
    public MyApplication(ServiceLocator serviceLocator) {
        packages(true, "my.domain.resource");

        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
        GuiceIntoHK2Bridge guiceBridge =
            serviceLocator.getService(GuiceIntoHK2Bridge.class);
        guiceBridge.bridgeGuiceInjector(
            Guice.createInjector(Stage.PRODUCTION,
                new MyModule()
            ));
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment