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.
@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();
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()
));
}
}