泽西岛-是否可以使用参数实例化每个请求资源? [英] Jersey - Is there a way to instantiate a Per-Request Resource with parameters?

查看:95
本文介绍了泽西岛-是否可以使用参数实例化每个请求资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个课程:

@Path("/test")
public class TestResource{

   private TestService testService;

   public TestResource(TestService testService){
      this.testService = testService;
   }

   @GET
   public String getMessage(){
      return testService.getMessage();
   }


}

然后,我想在Jersey上注册它.一个会做:

Then, I want to register it with Jersey. One would do:

 TestService testService = new TestServiceImpl();
 resourceConfig.register(new TestResource(testService));

但是问题在于该方法只生成一个TestResource实例.我想为每个请求创建一个实例.因此,泽西岛(Jersey)可以做到这一点:

But the problem is that approach makes a single instance of TestResource. I want to make an instance per request. So, Jersey has a way of doing this:

 TestService = new TestServiceImpl();
 resourceConfig.register(TestResource.class);

太好了!但这不允许我将实例化参数传递给其构造函数.

That is great! But it doesn't let me to pass instantiation parameters to its constructor.

最重要的是,我使用的是DropWizard,它也不允许我从ResourceConfig中访问所有方法(但是我检查了其文档,但没有找到任何可以让我传递参数的方法)

On top of this, I'm using DropWizard which also doesn't let me access all the methods from the ResourceConfig (but I checked its documentation and didn't find any method that let me pass parameters)

所以我想知道是否有一种方法可以实现这一目标.

So I was wondering if there is a way of achieving this.

谢谢!

PS:我知道我可以使用Spring或Guice(或我自己的实例提供程序)并注入我的类来解决这个问题,但是我不想这样做(当然,如果是唯一的话,我会这样做的)方式)

PS: I know I can get away with this using Spring or Guice (or my own instance provider) and injecting my classes, but I don't want to do that (of course I'll do it if it's the only way)

推荐答案

正如@peeskillet所提到的,球衣2.x与HK2紧密相连,这似乎是向其传递服务的唯一方法.

As @peeskillet has mentioned, jersey 2.x is tightly coupled with HK2 and it seems that it's the only way to pass a service to it.

@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);

这篇关于泽西岛-是否可以使用参数实例化每个请求资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆