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. |
$ 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
:
$ ./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 for more options.
To create a service that responds to “Hello World” you first need a controller. The following is an example:
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 @Controller annotation defines the class as a controller mapped to the path /hello |
2 | The @Get annotation maps the index method to all requests that use an HTTP GET |
3 | A 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:
$ curl http://localhost:8080/hello
Hello World