【问题标题】:PlayFramework Scala dependency Injection JavaxPlayFramework Scala 依赖注入 Javax
【发布时间】:2016-05-18 01:11:06
【问题描述】:

我是 Scala 和 PlayFramework 的新手,我正在尝试弄清楚如何进行依赖注入。我基本上想要一个将成为特征的文件并将其注入控制器。我的问题是我的 Controller 类没有看到我的 Trait 这是我的代码

个人资料特征

package traitss

import play.api.mvc._


trait ProfileTrait extends Controller {
    def Addone()
  }

然后我尝试将其注入到我的控制器中

import java.nio.file.{Files, Paths}

import traitss.ProfileTrait_
import play.api.mvc.{Action, Controller}
import javax.inject._

class Profiles @Inject() (profileTrait: ProfileTrait)   extends Controller
{

}

但是我的控制器没有看到它,我正在尝试按照https://www.playframework.com/documentation/2.5.x/ScalaDependencyInjection 的示例进行操作。 我正在使用播放框架版本 2.50

【问题讨论】:

  • 我去掉了下划线,但同样的问题仍然存在。
  • 首先,你不应该在控制器中注入控制器......如果你有一个公共服务,你应该在每个控制器中独立注入它。

标签: scala playframework playframework-2.5


【解决方案1】:

您不能直接注入特征。您需要指定需要注入的 trait 的实现。

有两种方法来指定要注入的特征的实现:

使用@ImplementedBy注解。这是一个简单的例子:

package traitss

import play.api.mvc._
import com.google.inject.ImplementedBy

@ImplementedBy(classOf[ProfileTraitImpl])
trait ProfileTrait extends Controller {
    def Addone()
}

class ProfileTraitImpl extends ProfileTrait {
    // your implementation goes here
}

使用Programmatic Bindings

package traitss

import play.api.mvc._
import com.google.inject.ImplementedBy

@ImplementedBy(classOf[ProfileTraitImpl])
trait ProfileTrait extends Controller {
    def Addone()
}

ProfileTraitImpl:

package traitss.impl

class ProfileTraitImpl extends ProfileTrait {
    // your implementation goes here
}

创建一个可以将实现与 trait 绑定的模块

import com.google.inject.AbstractModule

class Module extends AbstractModule {
  def configure() = {

    bind(classOf[ProfileTrait])
      .to(classOf[ProfileTraitImpl])
  }
}

通过使用模块方法,您可以获得启用或禁用绑定的额外好处。例如,在您的 application.conf 文件中,您可以使用 play.modules.enabled += module OR play.modules.disabled += module

启用/禁用模块

【讨论】:

    【解决方案2】:

    你不能注入一个特征,你必须注入一个实现该特征的对象。

    要使依赖注入起作用,您必须告诉框架(play 在后台使用 Guice)如何解析要注入的依赖。 有很多方法可以做到这一点,这取决于您的情况,有关更多详细信息,您可以查看Guice's documentation,最简单的方法是在您的app 目录中创建Module.scala,如果它还没有的话,并且放这样的东西:

    import com.google.inject.AbstractModule
    class Module extends AbstractModule {
      override def configure() = {
        bind(classOf[ProfileTrait]).toInstance( ... )
      }
    } 
    

    在... 中,您放置了创建要注入的对象的逻辑。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 2014-03-25
      • 2019-08-16
      • 1970-01-01
      相关资源
      最近更新 更多