Jersey and HK2 ServiceLocator

后端 未结 2 1084
自闭症患者
自闭症患者 2021-01-06 11:41

I\'m trying to initialize some components in my Jersey application in the Application constructor (the thing that inherits from ResourceConfig) . It looks like this

2条回答
  •  既然无缘
    2021-01-06 12:07

    I am going to assume you are starting up a servlet and have a class extending org.glassfish.jersey.server.ResourceConfig and your bindings are correctly registered (e.g. using a Binder and registerInstances). If you then want to access the ServiceLocator in order to perform additional initialization, you have two choices:

    One approach is to register a ContainerLifecycleListener (as seen here in this post):

    // In Application extends ResourceConfig constructor
    register(new ContainerLifecycleListener() {
    
            @Override
            public void onStartup(final Container container) {
                // access the ServiceLocator here
                final ServiceLocator serviceLocator = container.getApplicationHandler().getInjectionManager().getInstance(ServiceLocator.class);
    
                // Perform whatever with serviceLocator
            }
    
            @Override
            public void onReload(final Container container) {
                /* ... */}
    
            @Override
            public void onShutdown(final Container container) {
                /* ... */}
        });
    

    The second approach is to use a Feature, which can also be auto-discovered using @Provider:

    @Provider
    public final class StartupListener implements Feature {
    
        private final ServiceLocator sl;
    
        @Inject
        public ProvisionStartupListener(final ServiceLocator sl) {
            this.sl = sl;
        }
    
        @Override
        public boolean configure(final FeatureContext context) {
            // Perform whatever action with serviceLocator
            return true;
        }
    

提交回复
热议问题