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:
$ 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
:
$ ./gradlew run
> Task :run
[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:
import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
@Controller("/hello") (1)
public class HelloController {
@Get(produces = MediaType.TEXT_PLAIN) (2)
public String index() {
return "Hello World"; (3)
}
}
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller('/hello') (1)
class HelloController {
@Get(produces = MediaType.TEXT_PLAIN) (2)
String index() {
'Hello World' (3)
}
}
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
@Controller("/hello") (1)
class HelloController {
@Get(produces = [MediaType.TEXT_PLAIN]) (2)
fun index(): String {
return "Hello World" (3)
}
}
1 | The class is defined as a controller with the @Controller annotation mapped to the path /hello |
2 | The @Get annotation is used to map the index method to all requests that use an HTTP GET |
3 | A 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:
$ curl http://localhost:8080/hello
Hello World