简体   繁体   中英

Call grails plugin closure from Groovy class

I am using the AWS plugin for grails. I am trying to use the sesMail closure from a Groovy class, not a service or controller eg in a method:

String msgId = sesMail {

            from props.from
            replyTo props.replyTo
            to prop.to
            html props.body
        }

I am getting an error saying sesMail is not a method of the Groovy class. My questions are:

  1. How can I call a plugin closure that is ordinarily available in grails service and controllers from a regular Groovy class

  2. Following that I'm curious how these closures are defined and made available in the service and controller. I can't find a definition of sesMail in the plugin.

thanks

Good Question. And I appreciate that you are curious to find the root cause of your problem. Here are your answers:-

  • You can directly call the SendSesMail bean to send mail instead of calling the sesMail closure. Your groovy class would look like:

     class MyGroovyClass{ def sendSesMail def sendSomeMails(){ String msgId = sendSesMail.send{ from props.from replyTo props.replyTo to prop.to html props.body } } } 

    As you can see SendSesMail is not a service class it is just a POGO, so it will not be autowired in this groovy class unless you define that in resources.groovy . So:

Something like:

//resources.groovy
beans = {
   sendSesMail(grails.plugin.aws.ses.SendSesMail)
}

Also keep a note by using the above method directly you would be bypassing grails.plugin.aws.ses.enabled configuration. So you have to handle it explicitly.

  • You can very well find the definition of sesMail method which is metaClasses over target classes to take a Closure as an argument here in MetaClassInjector . This class is basically used to inject/add dynamicMethods from the plugin definition. You can find it as

AwsGrailsPlugin (Line: 37) --> AwsPluginSupport (Line: 86) --> MetaClassInjector (Line: 50)

You can also see in MetaClassInjector (around line 45 and 46), the target classes are controller and service classes. Hence you find the closure sesMail available in those 2 artefacts.

I hope it is clear enough to address your curiousness. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM