播放框架依赖注入 [英] Play Framework Dependency Injection

查看:89
本文介绍了播放框架依赖注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Google各处寻找有关如何在Play Framework 2.1中使用Guice/Spring DI的有用信息

I've been looking all over Google to find some useful information on how to use Guice/Spring DI in Play Framework 2.1

我要做的是在某些DAO中注入多个服务,反之亦然.

What I want to do is to Inject several Services in some DAO's and vice versa.

只需对此做些说明-对于play 2.1,您是否必须在路由文件中使用@注释进行DI?

Just need some clarification on this - With play 2.1, do you have to use an @ annotation within the routes file for DI?

我在这里查看了本指南-

I've looked at this guide here - https://github.com/playframework/Play20/blob/master/documentation/manual/javaGuide/main/inject/JavaInjection.md

并应用了以下步骤,在应用程序中创建Global类,并在Build.scala中添加GUICE依赖项,但是在对注入的对象进行调用时,始终会得到空指针异常.

and applied the following steps creating a Global class in app and adding the GUICE dependencies in Build.scala but keep on getting a null pointer exception when invoking on the injected object.

有人能够使用Guice在Play 2.1中使DI正常工作吗?我在互联网上看到过一些示例,但它们似乎都在控制器中使用了DI.

Has anyone been able to get DI working in Play 2.1 using Guice? I've seen examples across the internet but they all seem to be using DI within the controller.

推荐答案

我注意到您正在使用Java.这是我如何将其注入控制器中的方法.

I noticed you are using Java. Here is how I got it to work for injecting into a controller.

首先,我创建了以下4个类:

First, I created the following 4 classes :

MyController:

MyController:

package controllers;

import play.mvc.*;
import javax.inject.Inject;

public class MyController extends Controller {

@Inject
private MyInterface myInterface;
    public Result someActionMethodThatUsesMyInterface(){
        return ok(myInterface.foo());
    }
}

MyInterface:

MyInterface:

package models;

public interface MyInterface {
    String foo();
}

MyImplementation2Inject:

MyImplementation2Inject:

package models;

public class MyImplementation2Inject implements MyInterface {
    public String foo() { 
        return "Hi mom!";
    }
}

MyComponentModule:

MyComponentModule:

package modules;

import com.google.inject.AbstractModule;
import models.MyInterface;
import models.MyImplementation2Inject;

public class ComponentModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(MyInterface.class).
                to(MyImplementation2Inject.class);
    }
}

最后,我花了很长时间才弄明白的最后一部分是注册模块.为此,请在conf目录中的application.conf文件的末尾添加以下行:

Now the final part, that took me a silly long time to figure out, was to register the module. You do this by adding the following line to the end of the application.conf file, which is located in the conf directory:

play.modules.enabled += "modules.MyComponentModule"

我希望这对您有所帮助. :)

I hope this was helpful to you. :)

这篇关于播放框架依赖注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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