假设我有这样的课程:
@Path("/test")
public class TestResource{
private TestService testService;
public TestResource(TestService testService){
this.testService = testService;
}
@GET
public String getMessage(){
return testService.getMessage();
}
}
然后,我想在 Jersey 上注册它。一个会做:
TestService testService = new TestServiceImpl();
resourceConfig.register(new TestResource(testService));
但问题是该方法创建了 TestResource 的单个实例。我想为每个请求创建一个实例。因此,泽西岛有一个方法可以做到这一点:
TestService = new TestServiceImpl();
resourceConfig.register(TestResource.class);
太棒了!但它不允许我将实例化参数传递给其构造函数。
最重要的是,我使用的是 DropWizard,它也不允许我访问 ResourceConfig 中的所有方法(但我检查了它的文档,没有找到任何让我传递参数的方法)
所以我想知道是否有办法实现这一目标。
Thanks!
PS:我知道我可以使用 Spring 或 Guice (或我自己的实例提供程序)并注入我的类来摆脱这个问题,但我不想这样做(当然,如果这是唯一的方法,我会这样做)
正如 @peeskillet 提到的,jersey 2.x 与 HK2 紧密耦合,似乎这是向其传递服务的唯一方法。
@Singleton
@Path("/test")
public class TestResource {
private TestService testService;
@Inject
public TestResource(TestService testService){
this.testService = testService;
}
@GET
public String getMessage(){
return testService.getMessage();
}
}
这就是您注册的方式:
environment.jersey().register(new AbstractBinder(){
@Override
protected void configure() {
bind(TestServiceImpl.class).to(TestService.class);
// or
bind(new TestServiceImpl()).to(TestService.class);
});
environment.jersey().register(TestResource.class);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)