gpt4 book ai didi

java - Jersey 使用 Guice 测试依赖注入(inject)

转载 作者:搜寻专家 更新时间:2023-11-01 02:56:42 26 4
gpt4 key购买 nike

我无法将 JerseyTest (v2.25) 与 Guice 依赖注入(inject)一起使用。我当前的设置受到另一个 stackoverflow question 上的答案的启发。 .此设置仍然尝试通过 HK2 连接 @Provides 注释类的依赖项,但我的测试用例失败了。如果我从我的测试 ResourceConfig 中删除了 .packages() 调用,似乎监听器根本没有初始化,我的测试用例都返回 404。

这是我当前的 Jersey 测试设置:

public class MyTestSuite extends JerseyTest {

@Override
protected Application configure() {
return new ResourceConfig().packages("com.example.api");
}

@Override
protected DeploymentContext configureDeployment() {
return ServletDeploymentContext.builder(configure())
.addListener(GuiceConfig.class)
.addFilter(GuiceFilter.class, "guiceFilter")
.addFilter(ServletContainer.class, "jerseyFilter", Collections.singletonMap("javax.ws.rs.Application", JerseyConfig.class.getName()))
.build();
}
}

以下是部署上下文中引用的类:

public class GuiceConfig extends GuiceServletContextListener {
static Injector injector;

@Override
protected Injector getInjector() {
injector = Guice.createInjector(new WebModule());
return injector;
}
}
public class JerseyConfig extends ResourceConfig {

@Inject
public JerseyConfig(ServiceLocator serviceLocator) {
Injector injector = (Injector) serviceLocator.getService(ServletContext.class).getAttribute(Injector.class.getName());
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
serviceLocator.getService(GuiceIntoHK2Bridge.class).bridgeGuiceInjector(injector.createChildInjector(new HK2IntoGuiceBridge(serviceLocator)));
packages("com.example.api");
}
}
public class WebModule extends ServletModule {

@Override
protected void configureServlets() {
serve("/*").with(ServletContainer.class, Collections.singletonMap(ServletProperties.JAXRS_APPLICATION_CLASS, JerseyConfig.class.getName()));
}
}

最佳答案

无需自己编写,您可以使用现有库 Jersey Guice Module

you need to bridge the gap between the two DI frameworks. This module aims to do just that by booting Jetty based Jersey server and initializing the bridge between HK2 and Guice.

Getting Started

  • Add JerseyModule to your Guice Injector

  • Configure packages to scan for resources and a port to expose

  • Get instance of JerseyServer and start consuming your Restful resources

 compile 'io.logz:guice-jersey:1.0.8'

请注意您缺少 GuiceIntoHK2Bridge

Injector injector = (Injector) servletContext.getAttribute(Injector.class.getName()); 
GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge.class);
guiceBridge.bridgeGuiceInjector(injector);

关于java - Jersey 使用 Guice 测试依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872093/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com