gpt4 book ai didi

java - 如何将已经存在的对象注入(inject)到 Dagger 2 的对象图中?

转载 作者:行者123 更新时间:2023-12-02 13:00:38 26 4
gpt4 key购买 nike

我正在编写一个带有框架的 Web 应用程序,该框架调用我的 Application 类的 run() 方法并传入 Environment< 类型的对象.

我正在编写的其他对象依赖于此 Environment 类,因为它们需要调用其 register()metrics() 方法.

问题是我在应用程序的 main() 函数中创建对象图,如下所示:

public class MainApplication extends Application<MainConfiguration> {

private final ConnectionPool sharedPool;

public static void main(String[] args) throws Exception {
MainApplication mainApplication = DaggerMainApplicationComponent.create()
.createApplication();

mainApplication.run(args);
}

@Inject public MainApplication(ConnectionPool connectionPool) {
super();
sharedPool = connectionPool;
}

@Override
public void run(MainConfiguration configuration, Environment environment) throws Exception {
// Here is where I have access to the environment variable
}

因此,当 Dagger 构造 MainApplication 时,环境 变量尚未准备好。只有当 run() 被调用时它才可用。

有没有办法将此变量注入(inject)到对象图中?

最佳答案

这类问题已经引起了一些关注here但要回答您的具体情况并详细说明 EpicPandaForce的评论,您可以通过创建持有者类轻松逃脱小型依赖循环:

class EnvironmentHolder {

private Environment environment;

@Nullable
Environment get() {
return environment;
}

void set(Environment environment) {
this.environment = environment;
}
}

并将 Environment 的先前依赖项改为 EnvironmentHolder 的依赖项:

class DependsOnEnvironment {

private final EnvironmentHolder environmentHolder;

@Inject
DependsOnEnvironment(EnvironmentHolder environmentHolder) {
this.environmentHolder = environmentHolder;
}

public void doSomethingWithMetrics() {
Environment environment = environmentHolder.get();
if (environment == null) {
throw new IllegalStateException("Environment object should be available at the injection time of this class");
}

Metrics metrics = environment.metrics();
//etc.
}
}

如果您发现自己经常使用此功能,则可能表明您需要自定义范围。

关于java - 如何将已经存在的对象注入(inject)到 Dagger 2 的对象图中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44313590/

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