如何将一个已经存在的对象注入到 Dagger 2 的对象图中?

How can I inject an already existing object into the object graph in Dagger 2?

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

我正在编写的其他对象依赖于此 Environment class,因为它们需要调用其 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
}

所以,当 MainApplication 被 Dagger 构造时,environment 变量还没有准备好。只有在调用run()时才可用。

有没有办法在那个时候将这个变量注入到对象图中?

这类问题已经引起了一些关注 here but to answer your specific case and to elaborate on EpicPandaForce 的评论您可以通过创建持有者轻松摆脱小的依赖循环 class:

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.
    }
}

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