Java Guice - 使用静态辅助方法将依赖项注入到类中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18454790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:44:58  来源:igfitidea点击:

Guice - Inject dependency into a class with static helper methods

javaelguicestatic-methodstaglib

提问by Arman

I'm still new to Guice and haven't used any DI frameworks before. After reading the official wiki and many other documents I'm still unable to wrap my head around it completely.

我还是 Guice 的新手,之前没有使用过任何 DI 框架。在阅读了官方 wiki 和许多其他文档后,我仍然无法完全理解它。

In my particular case I want to write a EL taglib function that uses some other (to-be-injected) class. As all taglib functions have to be declared as static, I can't just @Inject my dependency via constructor or setter. I thought of using the requestStaticInjection() method described in http://code.google.com/p/google-guice/wiki/Injections#Static_Injectionsbut I unable to get it to work and haven't been able to find any good tutorial.

在我的特殊情况下,我想编写一个使用其他(待注入)类的 EL taglib 函数。由于所有 taglib 函数都必须声明为静态,因此我不能仅通过构造函数或 setter 来 @Inject 我的依赖项。我想过使用http://code.google.com/p/google-guice/wiki/Injections#Static_Injections 中描述的 requestStaticInjection() 方法,但我无法让它工作,也找不到任何好的教程。

Thanks in advance for any help,

在此先感谢您的帮助,

Arman

阿曼

采纳答案by condit

It doesn't get much more clear than that Guice documentation but here's a unit test that shows an example of how you can use static injection:

它没有比 Guice 文档更清楚,但这里有一个单元测试,显示了如何使用静态注入的示例:

public class StaticInjectionExample {

  static class SomeClass {}

  static class TagLib{
    @Inject
    static SomeClass injected;

    public static void taglibFunction(String foo) {
      injected.something(foo);
    }

  }

  static class TestModule extends AbstractModule {
    @Override
    protected void configure() {
      requestStaticInjection(TabLib.class);
    }
  }

  @Test
  public void test() {
    Injector injector = Guice.createInjector(new TestModule());
    TagLib receiver = injector.getInstance(TagLib.class);
    // Do something with receiver.injected
  }
}