繁体   English   中英

将Guice与Play一起使用:只能对静态字段进行注入

[英]Using Guice with Play: Injection possible for static fields only

我是Play的忠实拥护者,如今我几乎在任何我的项目中都使用它。 但是,随着我的项目之一变得更大,我决定包括一个DI解决方案。 在Spring和Guice之间进行了短暂的考虑之后,我停下了Guice并添加了Play的Guice模块( http://www.playframework.com/modules/guice-1.0/home )。

它的问题似乎是注入仅适用于静态场的事实。 这意味着我将必须执行以下操作:

@InjectSupport
public class MyService {

    @Inject
    static MyBean myBean;

}

来自( http://java.dzone.com/articles/dependency-injection-play

这让我有些害怕,尤其是在测试方面。 我的意思是,确实,大多数DI解决方案总是尝试注入单例,例如,Spring为每个bean创建一个实例并注入它,最后还是一样。 我应该担心这些吗?

您绝对可以通过Play执行Guice注入。

  • 您不应使用旧的Guice模块(1.0版)。 您所指的教程还使用了旧版Guice和旧版Play(1.2版!)

    请看一下新的Guice模块(3.0版)和Play(2.1.1版)

    http://www.playframework.com/documentation/2.1.1/JavaInjection

  • 注入实例变量时,需要动态创建控制器

    在您的路线文件中:

     GET / @controllers.Application.index() 

    在您的Global.java中,您需要重写getControllerInstance:

     @Override public <A> A getControllerInstance(Class<A> controllerClass) throws Exception { return INJECTOR.getInstance(controllerClass); } 

在Play 1中,您可以轻松地将正常的Guice单例与静态注入的控制器字段组合在一起,其窍门是使批注导入正确。

在您的播放控制器中,需要静态注入的作业和测试类使用JSR330注释版本:

import javax.inject.Inject;
public class Application extends Controller {
    @Inject private static MyService myService;
    ....
}

对于需要@InjectSupport的其他类,请使用JSR330 / module导入:

import play.modules.guice.InjectSupport;
import javax.inject.Inject;
@InjectSupport
public class AnotherClass  {
    @Inject private static MyService myService;
}

对于Guice库实例化的实际(非静态)服务,您需要使用Guice批注版本(请注意com.google.inject包):

import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class MyService {
    @Inject private AnotherService anotherService;  // note non-static injection
}

您还需要一个空模块来开始工作:

import com.google.inject.AbstractModule;
public class MainModule extends AbstractModule {
    @Override
    protected void configure() {}
}

这也应该适用于以@Singleton以外的其他方式创建的Guice类,例如@Provides,尽管我还没有尝试过。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM