我试图在资源构造函数中一起使用 Jersey 的 @QueryParam
和 Guice 的 @Inject
。网上查了一下,之前也有人问过类似的问题:
How can I mix Guice and Jersey injection?
http://users.jersey.dev.java.narkive.com/zlGMXuBe/can-queryparam-be-used-in-resource-constructor-along-with-guice-injection
看来是不可能了。然而,这些问题已经有好几年了,那么我现在尝试做的事情可能吗?
以下是我尝试执行的示例代码:
@Path("/mypath")
public class MyResource {
private Manager manager;
private String type;
@Inject
public MyResource(Manager manager,
@QueryParam("type") String type) {
this.manager = manager;
this.type = type;
}
@GET
@Produces("text/plan")
@Path("/{period}")
public String myMethod(@PathParam("period") String period) {
return manager.foo(period, type);
}
}
谢谢!
最佳答案
这对我有用。可能是Jersey和Guice的正确绑定(bind)有关的问题。
我使用您的资源定义和一些样板代码创建了一个最小的 Web 应用程序。
首先是应用程序初始化:
@WebListener
@Singleton
public class AppContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
new GuiceBootstrap().contextInitialized(sce);
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
// no op
}
}
你可以看到我在那里初始化了 Guice。这是 Guice 代码。
public class GuiceBootstrap extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector((Module) binder -> binder.bind(Manager.class)
.to(ManagerImpl.class));
}
}
它是 Java 8 语法,但如果您不使用 Java 8,它可以轻松转换为 pre-lambda 代码。我创建了一个只有一个绑定(bind)的 Guice 注入(inject)器。
Manager
和实现类非常简单。
public interface Manager {
String foo(String period, String type);
}
public class ManagerImpl implements Manager {
@Override
public String foo(String period, String type) {
return "Got " + period + " " + type;
}
}
最后是初始化 Jersey 并将其内部注入(inject)器 (HK2) 绑定(bind)到 Guice 的代码。
@ApplicationPath("api")
public class ApiRest extends ResourceConfig {
@Inject
public ApiRest(ServiceLocator serviceLocator, ServletContext servletContext) {
packages("net.sargue.so38531044");
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
Injector injector = (Injector) servletContext.getAttribute(Injector.class.getName());
if (injector == null)
throw new RuntimeException("Guice Injector not found");
guiceBridge.bridgeGuiceInjector(injector);
}
}
关于java - 如何在资源构造函数中使用 Jersey 的 @QueryParam 和 Guice 注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38531044/