Groovy Support in the CLI

The Micronaut Command Line Interface includes special support for Groovy. To create a Groovy application, use the groovy lang option. For example:

Create a Micronaut Groovy application

  1. $ mn create-app hello-world --lang groovy

The above generates a Groovy project, built with Gradle. Use the -build maven flag to generate a project built with Maven instead.

Once you have created an application with the groovy feature, commands like create-controller, create-client etc. generate Groovy files instead of Java. The following example demonstrates this when using interactive mode of the CLI:

Create a bean

  1. $ mn
  2. | Starting interactive mode...
  3. | Enter a command name to run. Use TAB for completion:
  4. mn>
  5. create-bean create-client create-controller
  6. create-job help
  7. mn> create-bean helloBean
  8. | Rendered template Bean.groovy to destination src/main/groovy/hello/world/HelloBean.groovy

The above example demonstrates creating a Groovy bean that looks like the following:

Micronaut Bean

  1. package hello.world
  2. import javax.inject.Singleton
  3. @Singleton
  4. class HelloBean {
  5. }
Groovy automatically imports groovy.lang.Singleton which can be confusing as it conflicts with javax.inject.Singleton. Make sure you use javax.inject.Singleton when declaring a Micronaut singleton bean to avoid surprising behavior.

We can also create a client - don’t forget Micronaut can act as a client or a server!

Create a client

  1. mn> create-client helloClient
  2. | Rendered template Client.groovy to destination src/main/groovy/hello/world/HelloClient.groovy

Micronaut Client

  1. package hello.world
  2. import io.micronaut.http.client.annotation.Client
  3. import io.micronaut.http.annotation.Get
  4. import io.micronaut.http.HttpStatus
  5. @Client("hello")
  6. interface HelloClient {
  7. @Get
  8. HttpStatus index()
  9. }

Now let’s create a controller:

Create a controller

  1. mn> create-controller helloController
  2. | Rendered template Controller.groovy to destination src/main/groovy/hello/world/HelloController.groovy
  3. | Rendered template ControllerSpec.groovy to destination src/test/groovy/hello/world/HelloControllerSpec.groovy
  4. mn>

Micronaut Controller

  1. package hello.world
  2. import io.micronaut.http.annotation.Controller
  3. import io.micronaut.http.annotation.Get
  4. import io.micronaut.http.HttpStatus
  5. @Controller("/hello")
  6. class HelloController {
  7. @Get
  8. HttpStatus index() {
  9. return HttpStatus.OK
  10. }
  11. }

As you can see from the output from the CLI, a Spock test was also generated for you which demonstrates how to test the controller:

HelloControllerSpec.groovy

  1. ...
  2. void "test index"() {
  3. given:
  4. HttpResponse response = client.toBlocking().exchange("/hello")
  5. expect:
  6. response.status == HttpStatus.OK
  7. }
  8. ...

Notice how you use Micronaut both as client and as a server to test itself.