1

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

4

1 回答 1

0

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

1)直接基于绑定实例化一个对象:

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

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

创建一个扩展 GlobalSettings 的 Global 类,并将接口绑定到 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 注释来获取接口的实例:

@Inject
private Test test;

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

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

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

Guice注射液如何使用?

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

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

于 2013-05-19T01:09:21.090 回答