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

查看:95
本文介绍了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_
    }
}

我想在这种情况下,解决方案是将$ code> @Provides 方法成为一个完整的提供者< Something> 类。这显然是一个简化的例子;我正在处理的代码有许多这样的 @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?

也许这反映了我的亲戚对圭的鄙视,但我遇到了一些我以前一直试图做的事情。我必须缺少一些东西...

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天全站免登陆