为什么要使用 guice-hk2-bridge?

bns*_*d55 1 java jersey guice hk2

我很抱歉这个愚蠢的问题,但我真的在寻找这个问题的答案,但没有得到明确的答案。

我知道 jersey 使用 hk2 作为默认 DI 并且因为 hk2 是性能损失,替代 DI 是 Guice 更好,我们需要使用 guice-hk2-bridge 配置 jersey 以使用 Guice。

问题是为什么?,为什么我们需要配置球衣?,为什么我们不能只使用com.google.inject.Inject代替javax.inject.Inject,只导入com.google.inject包来使用Guice ?

这座桥有什么重要的地方?,我尝试在没有 guice-hk2-bridge 的情况下工作,它对我来说效果很好......我确定我误解了一些东西......

谢谢

Pau*_*tha 9

我不确定您对注释编程有多少经验,但只是让您知道,它们背后没有魔法。它们只是元数据,由框架决定如何处理这些元数据。你说:“为什么我们不能切换javax.inject.Injectcom.google.inject.Inject,让吉斯的工作?” 表示对这个概念缺乏了解。

任何 DI 框架都是围绕一个容器构建的,以保存绑定到该系统的所有服务。对于 HK2,容器是ServiceLocator,对于 Spring,容器是ApplicationContext,对于 Guice,容器是Injector。话虽如此,Jersey与 HK2 1紧密结合。这意味着因为 HK2 与容器相关联,所以 Jersey 也与 this 相关联。因此,当在 Jersey 应用程序中查找服务时,将通过. 以以下为例ServiceLocatorServiceLocatorServiceLocator

@Path("customers")
public class CustomerResource {
    @Inject
    private CustomerService service;

    @GET
    public List<Customer> findAll() {
        return service.findAll();
    }
}
Run Code Online (Sandbox Code Playgroud)

有了上面,在引擎盖下的某个地方,以下(在伪代码中)将继续CustomerService注入CustomerResource

ServiceLocator locator = getServiceLocator();
CustomerService service = locator.getService(CustomerService.class);
Run Code Online (Sandbox Code Playgroud)

当我们让 Jersey 创建(管理其生命周期)资源 (the CustomerResource) 时,即使资源是ServiceLocator. 这就是我的意思,泽西岛的一切都与 HK2 和ServiceLocator.

因此,为了让我们引入另一个 DI 框架,我们需要利用ServiceLocator. 桥接器的作用是将 Guice 绑定Injector到 HK2,ServiceLocator以便Injector可以通过ServiceLocator. 如果CustomerService是绑定到 Guice 的服务Injector,那么将会发生的情况是 Jersey 会在 中寻找它ServiceLocator,而定位器会在 中Injector寻找它。这就是桥的作用。


1. 从 2.26 版本开始,Jersey 实际上与 HK2 断绝了紧密耦合的联系。解释起来很复杂,但简而言之,即使它们不再紧密耦合,我们仍然需要将 HK2 与 Jersey 一起使用。