gpt4 book ai didi

java - Dagger 2 在多个服务类中的一种依赖关系

转载 作者:太空宇宙 更新时间:2023-11-04 10:55:05 26 4
gpt4 key购买 nike

我想将自定义类作为依赖项注入(inject)不同的服务类中,但我无法使其工作。它总是以 NPE 结尾。这是我的示例(简单的 Java SE)...

我的主类让一切运行起来

    public class Main {
public static void main(String[] args) throws IOException, TimeoutException {
MyApplication MyApp = new MyApplication();
MyApp.execute();
}
}

MyApplication 类

public class MyApplication {

private MyApplicationComponent appComponent;

@Inject FooService fooService;
@Inject BarService barService;
@Inject BazService bazService;

public MyApplication() {
component = DaggerMyApplicationComponent.builder().build();
component.inject(this);
}

public void execute() {
fooService.doStuff();
barService.doStuff();

// this will happen in the FooService construct, see below
// bazService.doStuff();
}
}

Dagger 中定义的组件和模块类,不使用 @Inject 构造函数方式

@Singleton
@Component(modules = {MyApplicationModule.class})
public interface MyApplicationComponent {
void inject(MyApplication application);
}

@Module
public class MyApplicationModule {
@Singleton
@Provides
FooService provideFooService() {
return new FooService();
}

@Singleton
@Provides
BarService provideBarService() {
return new BarService();
}

@Provides
BazService provideBazService() {
return new BarService();
}
}

使用 MyApplicationModule 和 MyApplicationComponent 提供 Main.class 中所需的依赖项。我还想在 FooService 类中使用 BazService。因此我使用 @Inject 方式将其定义为 FooService.class 的依赖项。

在 FooService.class 中使用 BazService 的 @Inject

public class FooService {
@Inject BazService bazService;

public FooService(){}

public doStuff(){
bazService.doStuff();
}
}

由于 FooSerivce 类中未定义 bazService,运行 Main.class 始终在 NPE 内结束。我不认为我错过了在任何地方添加注释。我认为 Dagger 不会这样工作......有什么想法吗?

最佳答案

FooService 期望通过字段注入(inject)来注入(inject) bazService,但您在此之前调用了 bazService。如果您想在 FooService 的构造函数中调用 bazService.doStuff(),则必须使用构造函数注入(inject)。

关于java - Dagger 2 在多个服务类中的一种依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47397045/

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