使用Grails 3无法获取mailService对象的实例,DI无法正常工作:
的build.gradle
compile "org.grails.plugins:mail:1.0.7"
testCompile "org.grails.plugins:mail:1.0.7"
application.groovy
environments {
development {
//grails.logging.jul.usebridge = true
grails.plugin.springsecurity.debug.useFilter = true
grails {
mail {
host = "main.mydomain.com"
port = 25
username = "login"
password = "password"
props = ["mail.smtp.auth":"true"]
}
}
grails.mail.default.from="noreply@mydomain.com"
}
production {
grails.logging.jul.usebridge = false
}
}
的TestController:
import groovy.xml.MarkupBuilder
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.security.access.annotation.Secured
@Secured(["hasRole('PERM_LOGIN')"])
class TestLogController {
def Logger logger = LoggerFactory.getLogger(this.getClass())
def mailService
def index() {
logger.info("Hello");
mailService.sendMail {
to "user@daomain.com"
subject "Hello Fred"
text "How are you?"
}
}
}
发生以下错误:
Caused by NullPointerException: Cannot invoke method sendMail() on null object
->> 18 | index in TestLogController.groovy
因此,mailService尚未正确注入cotroller类或集成测试:
import grails.test.mixin.integration.Integration
import grails.util.Holders
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationContext
import spock.lang.Shared
import spock.lang.Specification
@Integration
class SendMailSpec extends Specification {
@Shared Logger logger
@Shared def mailService
def setup() {
logger = LoggerFactory.getLogger(this.getClass())
ApplicationContext ctx = Holders.grailsApplication.mainContext
mailService = ctx.getBean("mailService");
}
def cleanup() {
}
void "test mailService is not null"() {
expect:
mailService !=null
}
void "test send mail"() {
expect:"mail send"
mailService.sendMail {
to "user@domain.com"
subject "Hello Fred"
text "How are you?"
}
}
}
有什么问题??
更新:这是错误的邮件插件版本,这个工作正常:
compile "org.grails.plugins:mail:2.0.0.RC2"
答案 0 :(得分:4)
这是安装时的当前版本(在撰写本文时):
compile 'org.grails.plugins:mail:2.0.0.RC6'
这是主插件的链接(我不知道谷歌为什么只显示旧版本):
https://grails.org/plugins.html#plugin/mail
我希望这有助于某人