9.1.3 Groovy Functions
As is typical in Groovy, writing functions is much simpler than in Java or Kotlin.
If you have the Micronaut CLI installed you can quickly create a Groovy function with mn create-function hello-world —lang groovy |
To begin, add the function-groovy
dependency (instead of the provider-specific dependency) which provides additional AST transformations that make writing functions simpler.
implementation("io.micronaut:micronaut-function-groovy")
<dependency>
<groupId>io.micronaut</groupId>
<artifactId>micronaut-function-groovy</artifactId>
</dependency>
You can now create your function as a Groovy script, under src/main/groovy
. You will set your project’s main class property to this function (instead of FunctionApplication
as in Java/Kotlin). For example:
Example build.gradle
mainClassName = "example.HelloGroovyFunction"
HelloGroovyFunction.groovy
String hello(String name) {
"Hello ${name}!"
}
The function you define should follow the following rules:
Define no more than 2 inputs
Use either Java primitive or simple types or POJOs as the arguments and return values
In order to make use of dependency injection in your Groovy function, use the groovy.transform.Field
annotation transform in addition to the @Inject
annotation.
HelloGroovyFunction.groovy
import groovy.transform.Field
import javax.inject.Inject
@Field @Inject HelloService helloService
String hello(String name) {
helloService.hello(name)
}