如何注射注射器? [英] How to inject Injector?

查看:33
本文介绍了如何注射注射器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:我需要在某些 FooClass 中延迟依赖实例化,所以我将 Injector 作为构造函数参数传递给类.

Situation: i need lazy dependency instantiation in some FooClass, so i pass Injector to class as a constructor parameter.

private final Injector m_injector;

public FooClass(@Named("FooInjector") Injector injector) {
m_injector = injector;
}

但是 guice 不允许绑定核心类(注入器、模块等).有什么解决办法?

But guice doesn't permit to bind core classes (injectors, modules and etc). What is the solution?

推荐答案

您不应该直接使用 Injector.而是传入 Provider 代替.此外,您应该在使用 FooClass 的地方注入提供程序.

You should not be using the Injector directly. Rather pass in the Provider<FooClass> instead. Also, you should be injecting the provider in the places where you use FooClass.

private final Provider<FooClass> provider;

@Inject
public ClassWhereFooIsUsed(Provider<FooClass> provider) {
    this.provider = provider;
}

.... somewhere else
FooClass f = provider.get(); // This is lazy

这篇关于如何注射注射器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆