【问题标题】:Accessing Play Singleton methods访问 Play Singleton 方法
【发布时间】:2016-11-18 19:00:04
【问题描述】:

我有以下 Play Singleton:

package p1

@Singleton
class MySingleton @Inject() (system: ActorSystem, properties: Properties) {

    def someMethod = {
         // ........
    }
}

当我尝试从一个类访问方法someMethod() 时,即使我导入包,我也会收到一个编译错误,提示找不到该方法。如何解决这个问题?

【问题讨论】:

  • 您能说明一下您是如何注入和使用MySingletonsomeMethod 的吗?
  • 我没有注入方法,我只是声明导入,是这个问题吗?

标签: scala playframework playframework-2.5


【解决方案1】:

首先,为了访问类的方法,您必须拥有该类的实例。当您使用依赖注入时,您需要先将单例类注入到要使用该方法的类中。所以首先声明类让我们说Foo并使用Guice注释@Inject注入类MySingleton,然后一旦你获得类的引用(实例)。您可以使用 . 调用 someMethod

如果您想访问类中的方法,请说Foo。你需要注入类MySingleton

import p1.MySingleton

class Foo @Inject() (mySingleton: MySingleton) {

  //This line could be any where inside the class.
  mySingleton.someMethod

}

另一种使用 Guice 字段注入的方式。

import p1.MySingleton

class Foo () {
  @Inject val mySingleton: MySingleton

  //This line could be any where inside the class.
  mySingleton.someMethod

}

【讨论】:

    【解决方案2】:

    它不是一个真正的 Scala 单例,所以你不能静态访问someMethod@Singleton 注解告诉 DI 框架仅在应用程序中实例化 一个 MySingleton 类,以便注入它的所有组件都获得相同的实例。

    如果您想使用名为 Foo 的类中的 someMethod,您需要执行以下操作:

    class Foo @Inject() (ms: MySingleton) {
    
       // call it somewhere within the clas
       ms.someMethod()
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-05-11
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多