本文介绍了游戏框架和没有路由的吉塞的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有可能使用Guice注入依赖项而不必通过路由.如果可以的话,如何在我的应用程序中调用class Test @Inject()...?

I would like to know if it's possible to inject dependencies using Guice without having to pass by the routing.If it is how can I call my class Test @Inject()... within my application ?

推荐答案

我认为在Play框架中使用Guice有两种方法:

I think there are two ways to use Guice in Play framework:

1)根据绑定直接实例化对象:

将Guice添加到您的Build.scala应用依赖项

Add Guice to your Build.scala app dependencies

val appDependencies = Seq(
    "com.google.inject" % "guice" % "3.0"
)

创建一个Global类,该类扩展GlobalSettings,并将接口绑定到configure()中的实现:

Create a Global class, which extends GlobalSettings, and bind interface to implementation in configure():

public class Global extends GlobalSettings {

    private Injector injector = Guice.createInjector(new AbstractModule() {
        @Override
        protected void configure() {
            bind(TestInferface.class).to(TestImpl.class);
        }
    });

}

在Controller或任何其他类中,使用@Inject批注获取接口的实例:

In your Controller or any other class, use the @Inject annotation to get an instance of the interface:

@Inject
private Test test;

2)播放控制器的依赖注入

通过Guice覆盖GlobalSettings.getControllerInstance来管理控制器类的实例:

Override GlobalSettings.getControllerInstance to manage controller class instantiation either via Guice:

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

如何使用Guice注射液?

How to use the Guice injection?

GET     /test1                           @controllers.ApplicationTest1.index()
GET     /test2                           @controllers.ApplicationTest2.index()

以@开头的路由定义将由play.GlobalSettings#getControllerInstance方法管理.

Route definitions starting with @ will be managed by play.GlobalSettings#getControllerInstance method.

这篇关于游戏框架和没有路由的吉塞的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 00:49