不添加 Guice 注释的 Guice DI 绑定
Guice DI binding without adding Guice annotations
我有一个用例,我使用基于 Spring 的外部 jar,而我的代码在 Google guice 上。
我正在尝试通过编写模块在我的依赖 jar 的 class 中注入依赖。
外部 class:
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 成员为空,并且我得到了countEvent 和durationEvent 的NullPointerException。
我的代码使用以下提供程序 class 创建一个对象以与 PTRS class 绑定。
@Provides
PTRS new PTRS(Client client){
PTRS ptrs = new PTRS();
ptrs.setGeoServiceClient(client);
return ptrs;
}
如何在不更改外部 class 的情况下注入这两个依赖项?
注入一个MembersInjector
在 Guice 未创建的对象上填充 @Inject
-注释字段(并调用 @Inject
-注释方法)。 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 实例.但是,这里的最佳做法是注入尽可能窄的接口,以便于阅读和模拟。
我有一个用例,我使用基于 Spring 的外部 jar,而我的代码在 Google guice 上。
我正在尝试通过编写模块在我的依赖 jar 的 class 中注入依赖。
外部 class:
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 成员为空,并且我得到了countEvent 和durationEvent 的NullPointerException。
我的代码使用以下提供程序 class 创建一个对象以与 PTRS class 绑定。
@Provides
PTRS new PTRS(Client client){
PTRS ptrs = new PTRS();
ptrs.setGeoServiceClient(client);
return ptrs;
}
如何在不更改外部 class 的情况下注入这两个依赖项?
注入一个MembersInjector
在 Guice 未创建的对象上填充 @Inject
-注释字段(并调用 @Inject
-注释方法)。 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 实例.但是,这里的最佳做法是注入尽可能窄的接口,以便于阅读和模拟。