How to get HK2 ServiceLocator in Jersey 2.12?

对着背影说爱祢 提交于 2019-11-30 19:16:10

I was able to get a reference to ServiceLocator by registering a ContainerLifecycleListener.

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

This example stores the reference as a member variable of ResourceConfig which you can use elsewhere via an 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;
    }
}

then elsewhere:

MyService service
    = myResourceConfig.getServiceLocator().createAndInitialize(MyService.class);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!