如何配置HK2以使用com.google.inject包中的Guice @Inject注释?

时间:2016-08-25 12:47:22

标签: java dependency-injection guice hk2

我有一个基于Jersey 2,Guice 3.0技术的项目。 由于Jersey 2框架使用HK2,我必须配置HK2-Guice桥。

JerseyGuiceServletContextListener:

package com.example.core;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
public class JerseyGuiceServletContextListener extends GuiceServletContextListener {

    static Injector injector;

    @Override
    protected Injector getInjector() {
        injector = Guice.createInjector(new ServletModule() {
            @Override
            protected void configureServlets() {
                //some code here
            }
        });
        return injector;
    }
}

JerseyConfiguration:

package com.example.core;

import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.ServerProperties;
import org.jvnet.hk2.guice.bridge.api.GuiceBridge;
import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge;

import javax.inject.Inject;
//...

class JerseyConfiguration extends ResourceConfig {

    @Inject
    public JerseyConfiguration(ServiceLocator serviceLocator) {
        packages("com.example.ws");

        GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
        GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
        guiceBridge.bridgeGuiceInjector(JerseyGuiceServletContextListener.injector);
    }
}

如果我使用javax.inject.Inject注释注入一些类属性,那么一切正常。但是,当我使用com.google.inject.Inject注释时,我的类属性不会被注入&我试图使用这个属性时得到NullPointerException。

如何使用com.google.inject.Inject注释?

1 个答案:

答案 0 :(得分:0)

您可以为com.google.inject.Inject创建自己的InjectionResolver。以下示例将创建一个与完全的工具。但是,谷歌Inject和javax Inject之间可能存在微妙的差异,这些差异未在以下实现中捕获。如果您依赖任何这些差异,您可能需要在您的InjectionResolver实现中变得更聪明。然后,您还必须在某些Jersey绑定调用或其他绑定调用中注册您的InjectionResolver。这是基本的实现:

@Singleton
public class GuiceInjectResolver implements InjectionResolver<com.google.inject.Inject> {
    @Inject @Named(InjectionResolver.SYSTEM_RESOLVER_NAME)
    private InjectionResolver<Inject> systemResolver;

    /* (non-Javadoc)
     * @see org.glassfish.hk2.api.InjectionResolver#resolve(org.glassfish.hk2.api.Injectee, org.glassfish.hk2.api.ServiceHandle)
     */
    @Override
    public Object resolve(Injectee injectee, ServiceHandle<?> root) {
        return systemResolver.resolve(injectee, root);
    }

    /* (non-Javadoc)
     * @see org.glassfish.hk2.api.InjectionResolver#isConstructorParameterIndicator()
     */
    @Override
    public boolean isConstructorParameterIndicator() {
        return true;
    }

    /* (non-Javadoc)
     * @see org.glassfish.hk2.api.InjectionResolver#isMethodParameterIndicator()
     */
    @Override
    public boolean isMethodParameterIndicator() {
        return true;
    }

}