how plugin works with inject and object instead of class in play 2.4

依然范特西╮ 提交于 2019-12-11 03:08:08

问题


I need to migrate the play mailer plugin for play 2.4.I checked some samples for play 2.4 and found that all the samples uses classes for plugin. I don't want to convert it to class. Is there any way for it to work with Object?

Sample

class MyComponent @Inject() (mailerClient: MailerClient) {
    def sendEmail {
       val email = Email(......)
       ......
       mailerClient.send(email)
    }
}

Original Code

object MailHandler{
  def sendEmail(to: String) = {
try {
  val email = play.api.libs.mailer.Email(...)
  MailerPlugin.send(email)
}catch{
  case ex:Exception=>PlayLogger.instance.error(ex.getMessage)
}
}

回答1:


I assume you use an object instead of a class in order to make it a singleton.

There is a special annotation for singletons (-> @Singleton) which makes sure there is only one instance of your class created.

Although they still use an actual class instead of an object.

An example could look like this:

import javax.inject._

@Singleton
class MailerClient {
  def sendEmail(to: String) = {
    try {
      val email = play.api.libs.mailer.Email(...)
       MailerPlugin.send(email)
    }catch{
      case ex:Exception=>PlayLogger.instance.error(ex.getMessage)
    }
  }
}

Have a look at the documentation: https://www.playframework.com/documentation/2.4.x/ScalaDependencyInjection#Singletons



来源:https://stackoverflow.com/questions/31198534/how-plugin-works-with-inject-and-object-instead-of-class-in-play-2-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!