gpt4 book ai didi

java - Guice DI 绑定(bind),无需添加 Guice 注解

转载 作者:行者123 更新时间:2023-11-30 02:19:35 25 4
gpt4 key购买 nike

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

我正在尝试通过编写模块将依赖项注入(inject)到我的依赖项 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 和urationEvent 的 NullPointerException。

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

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

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

最佳答案

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

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

如果您有权访问本身可注入(inject)的Injector,则可以调用 injectMembers(Class)直接调用,或者调用 getMembersInjector 来获取您选择的类型的 MembersInjector 实例。然而,这里的最佳实践是注入(inject)尽可能窄的接口(interface),以便阅读清晰并易于模拟。

关于java - Guice DI 绑定(bind),无需添加 Guice 注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47253540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com