Groovy Support in the CLI
The Command Line Interface for Micronaut includes special support for Groovy. To create a Groovy application use the groovy
lang option. For example:
Create a Micronaut Groovy application
$ mn create-app hello-world --lang groovy
The above will generate a Groovy project, built with Gradle. You can 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. will generate Groovy files instead of Java. The following example demonstrates this action when using interactive mode of the CLI:
Create a bean
$ mn
| Starting interactive mode...
| Enter a command name to run. Use TAB for completion:
mn>
create-bean create-client create-controller
create-job help
mn> create-bean helloBean
| 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
package hello.world
import javax.inject.Singleton
@Singleton
class HelloBean {
}
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
mn> create-client helloClient
| Rendered template Client.groovy to destination src/main/groovy/hello/world/HelloClient.groovy
Micronaut Client
package hello.world
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.annotation.Get
import io.micronaut.http.HttpStatus
@Client("hello")
interface HelloClient {
@Get
HttpStatus index()
}
Now let’s create a controller:
Create a controller
mn> create-controller helloController
| Rendered template Controller.groovy to destination src/main/groovy/hello/world/HelloController.groovy
| Rendered template ControllerSpec.groovy to destination src/test/groovy/hello/world/HelloControllerSpec.groovy
mn>
Micronaut Controller
package hello.world
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.HttpStatus
@Controller("/hello")
class HelloController {
@Get
HttpStatus index() {
return HttpStatus.OK
}
}
As you can see from the output from the CLI a Spock test was also generated for you demonstrating how to test the controller:
HelloControllerSpec.groovy
...
void "test index"() {
given:
HttpResponse response = client.toBlocking().exchange("/hello")
expect:
response.status == HttpStatus.OK
}
...
Notice how you use Micronaut both as client and as a server to test itself.