【问题标题】:Guice DI binding without adding Guice annotations不添加 Guice 注释的 Guice DI 绑定
【发布时间】:2018-04-25 11:57:42
【问题描述】:

我有一个用例,我使用基于 Spring 的外部 jar,而我的代码在 Google guice 上。

我正在尝试通过编写模块在我的依赖 jar 的此类中注入依赖项。

外部类:

public class PTRS {
    @Inject
    private Event countEvent;
    @Inject
    private Event durationEvent;
    private GeoServiceClient gClient;
    public void setGeoServiceClient(GeoServiceClient client){this.gClient=client}

}

我可以在我的模块的@provides 方法中使用setter 设置成员,但是@inject 成员有null,并且我得到countEvent 和durationEvent 的NullPointerException。

我的代码使用以下提供程序类来创建一个与 PTRS 类绑定的对象。

@Provides
PTRS new PTRS(Client client){
PTRS ptrs = new PTRS();
ptrs.setGeoServiceClient(client);
return ptrs;
}

如何在不更改外部类的情况下注入这两个依赖项?

【问题讨论】:

    标签: java spring dependency-injection guice inject


    【解决方案1】:

    注入MembersInjector 在 Guice 未创建的对象上填充 @Inject-annotated 字段(并调用 @Inject-annotated 方法)。 Guice 在 wiki 中将其称为 "On-demand injection",尽管我在其他地方没有听说过这个词。

    @Provides
    PTRS newPTRS(Client client, MembersInjector<PTRS> ptrsInjector){
      PTRS ptrs = new PTRS();
      ptrsInjector.injectMembers(ptrs);    // <-- inject members here
      ptrs.setGeoServiceClient(client);
      return ptrs;
    }
    

    如果您有权访问本身可注入的Injector,则可以直接调用injectMembers(Class),或调用getMembersInjector 以获取您选择的类型的MembersInjector 实例。但是,这里的最佳做法是注入尽可能窄的接口,以便于阅读和模拟。

    【讨论】:

      猜你喜欢
      • 2013-09-17
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 2013-09-29
      相关资源
      最近更新 更多