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.

  1. implementation("io.micronaut:micronaut-function-groovy")
  1. <dependency>
  2. <groupId>io.micronaut</groupId>
  3. <artifactId>micronaut-function-groovy</artifactId>
  4. </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

  1. mainClassName = "example.HelloGroovyFunction"

HelloGroovyFunction.groovy

  1. String hello(String name) {
  2. "Hello ${name}!"
  3. }

The function you define should follow the following rules:

  1. Define no more than 2 inputs

  2. 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

  1. import groovy.transform.Field
  2. import javax.inject.Inject
  3. @Field @Inject HelloService helloService
  4. String hello(String name) {
  5. helloService.hello(name)
  6. }