且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Dropwizard + Jersey:“不在请求范围内";创建自定义注释时

更新时间:2022-06-27 05:53:41

这是奇怪的行为.但看起来正在发生的是以下

This is weird behavior. But what looks like is going on is the following

  1. 您已将 TaskResource 注册为实例而不是 .class.这我很确定(虽然你没有提到).

  1. You have registered TaskResource as an instance and not as a .class. This I'm pretty sure of (though you have not mentioned).

register(new TaskResource()); 
/* instead of */ 
register(TaskResource.class);

做前者,它将资源设置在单例范围内.后者在请求范围内(除非另有注释 - 见下文)

Doing the former, it set the resource in a singleton scope. The latter in a request scope (unless annotated otherwise - see below)

加载资源模型时,它看到 TaskResource 是一个单例,并且 HttpServletRequest 在请求范围内.那个或那个工厂在每个请求范围内.我猜是两者之一.

When the resource model is loading it sees the TaskResource is a singleton, and that the HttpServletRequest is in a request scope. Either that or that the factory is in a per request scope. I'm guessing one of the two.

我认为它实际上可能一个范围问题,如错误消息中所述,但我非常确定的是,在运行时,它将使用线程本地代理进行处理,因为范围较小.

I thought that it might actually be a scope issue, as mentioned in the error message, but what I'm pretty sure of is that at runtime, it will get handled with a thread local proxy, because of the lesser scope.

您可以通过将 TaskResource 注册为一个类,然后使用 @Singleton 注释 TaskResource 来查看它是否已修复.这是如果您确实确实希望资源类成为单例.如果没有,那么就不要使用 @Singleton.

You can see it fixed by registering the TaskResource as a class, and then annotating the TaskResource with @Singleton. This is if you actually do want the resource class to be a singleton. If not, then just leave off the @Singleton.

对我来说奇怪的是,当资源在启动时显式实例化时,它在启动时失败,但在第一个请求加载框架时有效(这就是将它注册为类时发生的情况).它们都仍处于单例范围内.

The odd thing to me is that it the fact that it fails on startup when the resource is explicitly instantiated on startup, but works when the framework loads on the first request (which is what happens when you register it as a class). They are both still in a singleton scope.

您可能需要考虑的一件事是您是否真的希望资源成为单例.您确实必须担心单例的线程安全问题,并且还有一些其他限制.就个人而言,我更喜欢将它们保留在请求范围内.您必须进行一些性能测试,以查看是否会对您的应用程序产生很大影响.

One thing you might want to take into consideration is whether you actually want the resource to be a singleton or not. You do have to worry about thread safety issues with singletons, and there are are some other limitations. Personally, I prefer to keep them in a request scope. You would have to do some performance testing to see if there is much of an impact for your application.

对于参数注入,您可能需要查看这篇文章

For parameter injection you may want to take a look at this post

另见

  • jersey 2 context injection based upon HttpRequest without singleton. My answer should shed some more light.