<dependency>
<groupId>org.glassfish.hk2</groupId>
<artifactId>guice-bridge</artifactId>
<version>${hk2.version}</version>
</dependency>
这是一个使用 Guice 3.0 和 HK2 2.3.0(与 Jersey 2.13 捆绑在一起)的示例。这只是一个独立的,但它应该在 Jersey 环境中同样工作。
Guice 类
public class GuiceGreeter {
public String getGreeting(String name) {
return "Hello, " + name;
}
}
import com.google.inject.assistedinject.Assisted;
import javax.inject.Inject;
public class Message {
private final String message;
@Inject
public Message(GuiceGreeter greeter, @Assisted String name) {
message = greeter.getGreeting(name);
}
public String getMessage() {
return message;
}
}
public interface GuiceMessageFactory {
public Message getMessage(String name);
}
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
public class GuiceMessageModule extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder().build(GuiceMessageFactory.class));
bind(GuiceGreeter.class);
}
}
HK2服务,注入Guice工厂
import javax.inject.Inject;
public class HK2Service {
private final GuiceMessageFactory messageFactory;
@Inject
public HK2Service(GuiceMessageFactory messageFactory) {
this.messageFactory = messageFactory;
}
public void printMessage(String name) {
System.out.println(messageFactory.getMessage(name).getMessage());
}
}
主要的
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.api.ServiceLocatorFactory;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
import org.jvnet.hk2.guice.bridge.api.GuiceBridge;
import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge;
public class Main {
public static void main(String[] args) {
// Create service locator. In Jersey context, you should be able to
// inject the `ServiceLocator` into the `Application/ResourceConfig`
// subclass constructor, or as a field
ServiceLocatorFactory factory = ServiceLocatorFactory.getInstance();
ServiceLocator locator = factory.create("SimpleServiceLocator");
// bridge the two frameworks to allow Guice injected services
GuiceBridge.getGuiceBridge().initializeGuiceBridge(locator);
Injector injector = Guice.createInjector(new GuiceMessageModule());
GuiceIntoHK2Bridge guiceBridge = locator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(injector);
// Add my HK2 Service
ServiceLocatorUtilities.addClasses(locator, HK2Service.class);
// Look up HK2 service. If this lookup works, `@Inject` in Jersey should.
HK2Service service = locator.getService(HK2Service.class);
service.printMessage("peeskillet");
}
}
这打印出来"Hello, peeskillet"
。请参阅下面的评论以在 Jersey 应用程序main
中获取方法。ServiceLocator
如果您对 不熟悉,ServiceLocator
您使用 an 添加的所有绑定也AbstractBinder
将放入服务定位器上下文中,因此您不必像我上面提到的那样显式添加类HK2Service
。