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:

Applications generated via our CLI include Gradle or Maven wrappers, so it is not even necessary to have Gradle or Maven installed on your machine to begin running the applications. Simply use the mvnw or gradlew command, as explained further below.
  1. $ mn create-app hello-world
Supply —build maven to create a Maven-based build instead

The previous command creates a new Java application in a directory called hello-world featuring a Gradle build. You can run the application 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 for more options.

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

  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 @Controller annotation defines the class as a controller mapped to the path /hello
2The @Get annotation maps the index method to all requests that use an HTTP GET
3A String “Hello World” is returned as the response

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

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

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