How to get HK2 ServiceLocator in Jersey 2.12?

I would like to create a singleton instance of a class that is not involved in Jersey as a resource or service, and still want its dependencies to be injected from Jersey customer service.

I can register this class manually in my ResourceConfig constructor, then the ResourceConfig is passed to the Grizzly factory method, for example:

ResourceConfig resourceConfig = new DeviceServiceApplication(); LOGGER.info("Starting grizzly2..."); return GrizzlyHttpServerFactory.createHttpServer(BASE_URI, resourceConfig, mServiceLocator); 

The problem remains how to get a link to the ServiceLocator service in Jersey so that I can call createAndInitialize () to get my object with nested dependencies. I see that in versions of previous versions there were constructor options that expect ApplicationHandler, which, of course, provides access to the service locator (how I initialize this is another matter). You can also see that I tried passing in the parent ServiceLocator, but, of course, the resolution comes from child-> parent locator, and not in the other direction, so the parent request for my object is not executed, because the Jersey types are @Contract and @Service are not visible here.

Do I need to use something other than GrizzlyHttpServerFactory? I refuse and manually connect my singleton dependencies?

+6
source share
1 answer

I managed to get a link to ServiceLocator by registering a ContainerLifecycleListener .

In the onStartup(Container container) method, call container.getApplicationHandler().getServiceLocator() .

This example stores the link as a ResourceConfig member variable, which you can use elsewhere through the accessor.

 class MyResourceConfig extends ResourceConfig { // won't be initialized until onStartup() ServiceLocator serviceLocator; public MyResourceConfig() { register(new ContainerLifecycleListener() { public void onStartup(Container container) { // access the ServiceLocator here serviceLocator = container.getApplicationHandler().getServiceLocator(); // ... do what you need with ServiceLocator ... MyService service = serviceLocator.createAndInitialize(MyService.class); } public void onReload(Container container) {/*...*/} public void onShutdown(Container container) {/*...*/} }); } public ServiceLocator getServiceLocator() { return serviceLocator; } } 

and then in another place:

 MyService service = myResourceConfig.getServiceLocator().createAndInitialize(MyService.class); 
+12
source

Source: https://habr.com/ru/post/974964/


All Articles