我有一个基于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
注释?
答案 0 :(得分:0)
您可以为com.google.inject.Inject创建自己的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;
}
}