“还是一些HK2注释或技巧?”
您可以使用HK2的即时范围。只需使用注释资源类
@Immediate(其行为类似
@Singleton,这样就可以摆脱它),然后在上启用直接作用域
ServiceLocator。一个例子:
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,如在链接问题中一样,则可以创建一个
Feature并注册该功能,如本答案所示。
处理的一种方法ServiceLocator是实现Feature。
import javax.inject.Inject;import javax.ws.rs.core.Feature;import javax.ws.rs.core.FeatureContext;import org.glassfish.hk2.api.ServiceLocator;import org.glassfish.hk2.utilities.ServiceLocatorUtilities;public class ImmediateFeature implements Feature { @Inject public ImmediateFeature(ServiceLocator locator) { ServiceLocatorUtilities.enableImmediateScope(locator); } @Override public boolean configure(FeatureContext context) { return true; } }然后只需注册 Feature
ResourceConfig rc = new ResourceConfig().packages("jersey.hk2.test");rc.register(ImmediateFeature.class);我已经测试过了,效果很好
更新2
请参阅相关问题
更新3
看起来以前链接到的即时作用域内存泄漏问题已在2.22.1版中解决



