如何让我的Jersey 2端点在启动时急切地初始化? [英] How do I get my Jersey 2 Endpoints to eagerly initialize on startup?
问题描述
我正在从Jersey 1.x移植一些代码,并且我对各种运行状况检查端点的实现依赖于在启动时初始化的所有 @Singleton
端点资源,以便能够检测出要执行的检查。
I am porting some code from Jersey 1.x and my implementation of various Health Check endpoints relies on all the @Singleton
endpoint resources being initialized at start up so as to be able to detect which checks to do.
在Jersey 2.0中 - 无论我做什么,我似乎无法让我的资源端点在启动时初始化,它们只是当第一次访问每一个时,构造+初始化。
In Jersey 2.0 - whatever I do I can't seem to get my resource endpoints to initialise at start up and they are only constructed+initialized when each one is accessed for the first time.
我想我可以在应用程序
但是我宁愿使用包扫描!
I guess I could initialise them myself in the Application
class but I'd rather use the package scanning!
有没有人知道是否有一些配置选项会告诉Jersey 2急切地初始化所有资源端点它在包扫描期间发现?
Does anyone have any idea if there is some config option that will tell Jersey 2 to eagerly initialise all resource endpoints that it finds during package scanning?
或某些HK2注释或技巧?
Or some HK2 annotation or trick?
推荐答案
或某些HK2注释或技巧?
"Or some HK2 annotation or trick?"
你可以使用HK2的即时范围。只需使用 <$注释资源类c $ c> @Immediate (其作用类似于 @Singleton
,所以你可以摆脱它),然后立即启用 ServiceLocator
上的范围。例如:
You can use HK2's Immediate Scope. Just annotate the resource class with @Immediate
(which acts like @Singleton
, so you can get rid of that), then enable the immediate scope on the ServiceLocator
. An example:
import org.glassfish.hk2.api.ServiceLocator;
import org.glassfish.hk2.utilities.ServiceLocatorUtilities;
...
@ApplicationPath("/rest")
public class JerseyApplication extends ResourceConfig {
@Inject
public JerseyApplication(ServiceLocator locator) {
ServiceLocatorUtilities.enableImmediateScope(locator);
packages("thepackages.to.scan");
}
}
更新
根据此相关问题,如果您需要显式实例化 ResourceConfig
,就链接问题而言,您可以创建功能
并注册该功能,如此答案所示
UPDATE
Based on this related question, if you need to explicitly instantiate the ResourceConfig
, as in the case of the linked question, you can create a Feature
and register the feature, as seen in this answer
请参阅相关问题
看起来先前链接的立即范围内存泄漏问题已在版本2.22.1中得到解决
Looks like Immediate scope memory leak issue previously linked to has been resolved in version 2.22.1
这篇关于如何让我的Jersey 2端点在启动时急切地初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!