2.2 Creating a Server Application

Although not required to use Micronaut, the Micronaut CLI is the quickest way to create a new server application.

Using the CLI you can create a new Micronaut application in either Groovy, Java or Kotlin (the default is Java).

The following command creates a new “Hello World” server application in Java with a Gradle build:

  1. $ mn create-app hello-world
You can supply —build maven if you wish to create a Maven based build instead

The previous command will create a new Java application in a directory called hello-world featuring a Gradle build. The application can be run with ./gradlew run:

  1. $ ./gradlew run
  2. > Task :run
  3. [main] INFO io.micronaut.runtime.Micronaut - Startup completed in 972ms. Server Running: http://localhost:28933

If you have created a Maven based project, use ./mvnw mn:run instead.

For Windows the ./ before commands is not needed

By default the Micronaut HTTP server is configured to run on port 8080. See the section Running Server on a Specific Port in the user guide for more options.

In order to create a service that responds to “Hello World” you first need a controller. The following is an example of a controller:

  1. import io.micronaut.http.MediaType;
  2. import io.micronaut.http.annotation.Controller;
  3. import io.micronaut.http.annotation.Get;
  4. @Controller("/hello") (1)
  5. public class HelloController {
  6. @Get(produces = MediaType.TEXT_PLAIN) (2)
  7. public String index() {
  8. return "Hello World"; (3)
  9. }
  10. }
  1. import io.micronaut.http.MediaType
  2. import io.micronaut.http.annotation.Controller
  3. import io.micronaut.http.annotation.Get
  4. @Controller('/hello') (1)
  5. class HelloController {
  6. @Get(produces = MediaType.TEXT_PLAIN) (2)
  7. String index() {
  8. 'Hello World' (3)
  9. }
  10. }
  1. import io.micronaut.http.MediaType
  2. import io.micronaut.http.annotation.Controller
  3. import io.micronaut.http.annotation.Get
  4. @Controller("/hello") (1)
  5. class HelloController {
  6. @Get(produces = [MediaType.TEXT_PLAIN]) (2)
  7. fun index(): String {
  8. return "Hello World" (3)
  9. }
  10. }
1The class is defined as a controller with the @Controller annotation mapped to the path /hello
2The @Get annotation is used to map the index method to all requests that use an HTTP GET
3A String “Hello World” is returned as the result

If you are using Java, place the previous file in src/main/java/hello/world.
If you are using Groovy, place the previous file in src/main/groovy/hello/world.
If you are using Kotlin, place the previous file in src/main/kotlin/hello/world.

If you start the application and send a request to the /hello URI then the text “Hello World” is returned:

  1. $ curl http://localhost:8080/hello
  2. Hello World