Guice-使用静态助手方法将依赖项注入类 [英] Guice - Inject dependency into a class with static helper methods

查看:262
本文介绍了Guice-使用静态助手方法将依赖项注入类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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_Injections but I unable to get it to work and haven't been able to find any good tutorial.

谢谢

Arman

推荐答案

不会比Guice文档更加清楚,但是下面的单元测试显示了如何使用静态注入的示例:

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:

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

这篇关于Guice-使用静态助手方法将依赖项注入类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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