Guice:是否可以注入模块? [英] Guice: is it possible to inject modules?

查看:34
本文介绍了Guice:是否可以注入模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要一些 Depedency 的模块.有没有办法可以注入模块本身?我意识到这有点鸡和蛋的情况......

I have a Module that requires some Depedency. Is there a way Modules themselves can be injected? I realize this is a bit of a chicken and egg situation...

示例:

public class MyModule implements Module {

    private final Dependency d_;

    @Inject public MyModule(Dependency d) {
        d_ = d;
    }

    public void configure(Binder b) { }

    @Provides Something provideSomething() {
        // this requires d_
    }
}

我想在这种情况下,解决方案是将 @Provides 方法转换为成熟的 Provider 类.这显然是一个简化的例子;我正在处理的代码有许多这样的 @Provides 方法,因此将它们每个切割成单独的 Provider<...> 类并引入一个模块来配置它们添加一个相当多的混乱 - 我认为 Guice 是为了减少样板混乱?

I suppose in this case the solution would be to turn the @Provides method into a full-fledged Provider<Something> class. This is clearly a simplified example; the code I'm dealing with has many such @Provides methods so cutting them each into individual Provider<...> classes and introducing a module to configure them adds a fair amount of clutter - and I thought Guice was all about reducing boilerplate clutter?

也许这反映了我对 Guice 的相对笨拙,但我遇到过一些我很想执行上述操作的案例.我一定是遗漏了什么……

Perhaps it's a reflection of my relative noobyness to Guice but I've come across a fair few cases where I've been tempted to do the above. I must be missing something...

推荐答案

@Provides 方法可以将依赖项作为参数,就像 @Inject 注释的构造函数或方法的参数一样:

@Provides methods can take dependencies as parameters just like parameters to an @Inject annotated constructor or method:

@Provides Something provideSomething(Dependency d) {
   return new Something(d); // or whatever
}

这在此处有记录,但也许可以使其更加突出.

This is documented here, though perhaps it could be made to stand out more.

这篇关于Guice:是否可以注入模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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