问题描述
我需要将play mailer插件迁移到play 2.4.我检查了play 2.4的一些示例,发现所有示例都使用了插件类.我不想将其转换为类.它可以与Object一起使用吗?
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?
样品
class MyComponent @Inject() (mailerClient: MailerClient) {
def sendEmail {
val email = Email(......)
......
mailerClient.send(email)
}
}
原始代码
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)
}
}
推荐答案
我假设您使用一个对象而不是一个类来使它成为单例.
I assume you use an object instead of a class in order to make it a singleton.
有一个用于单例的特殊注释(-> @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.
一个例子可能像这样:
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)
}
}
}
看一下文档: https://www.playframework.com/documentation/2.4.x/ScalaDependencyInjection#Singletons
这篇关于插件如何与注入和对象(而不是播放2.4中的类)一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!