问题
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