Creando su primera aplicación
Learn how to create a Hello World Quarkus app. This guide covers:
-
Puesta en marcha de una aplicación
-
Creating a Jakarta REST endpoint
-
Inyección de beans
-
Pruebas funcionales
-
Packaging de la aplicación
1. Requisitos previos
To complete this guide, you need:
-
Roughly 15 minutes
-
An IDE
-
JDK 17+ installed with
JAVA_HOME
configured appropriately -
Apache Maven 3.9.8
-
Optionally the Quarkus CLI if you want to use it
Verifique que Maven está usando el Java que espera
If you have multiple JDK’s installed, it is not certain Maven will pick up the expected java
and you could end up with unexpected results.
You can verify which JDK Maven uses by running |
2. Arquitectura
In this guide, we create a straightforward application serving a hello
endpoint. To demonstrate
dependency injection, this endpoint uses a greeting
bean.
Esta guía también cubre las pruebas del endpoint.
3. Solución
We recommend that you follow the instructions from Bootstrapping the project and onwards to create the application step by step.
Sin embargo, puede ir directamente al ejemplo completo.
Descarga un archive o clona el repositorio git:
git clone https://github.com/quarkusio/quarkus-quickstarts.git
The solution is located in the getting-started
directory.
4. Puesta en marcha del proyecto
La forma más fácil de crear un nuevo proyecto de Quarkus es abrir un terminal y ejecutar el siguiente comando:
For Windows users:
-
If using cmd, (don’t use backward slash
\
and put everything on the same line) -
If using Powershell, wrap
-D
parameters in double quotes e.g."-DprojectArtifactId=getting-started"
Genera lo siguiente en ./getting-started
:
-
la estructura de Maven
-
un recurso de
org.acme.GreetingResource
expuesto en/hello
-
una prueba unitaria asociada
-
una página inicial que es accesible en
<a href="http://localhost:8080" class="bare">http://localhost:8080</a>
después de iniciar la aplicación -
ejemplo
Dockerfile
archivos para los modosnative
yjvm
ensrc/main/docker
-
el archivo de configuración de la aplicación
Once generated, look at the pom.xml
.
You will find the import of the Quarkus BOM, allowing you to omit the version of the different Quarkus dependencies.
In addition, you can see the quarkus-maven-plugin
responsible of the packaging of the application and also providing the development mode.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>${quarkus.platform.artifact-id}</artifactId>
<version>${quarkus.platform.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>${quarkus.platform.group-id}</groupId>
<artifactId>quarkus-maven-plugin</artifactId>
<version>${quarkus.platform.version}</version>
<extensions>true</extensions>
<executions>
<execution>
<goals>
<goal>build</goal>
<goal>generate-code</goal>
<goal>generate-code-tests</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
En un proyecto Gradle, se encontraría una configuración similar:
-
el plugin Quarkus Gradle
-
una directiva
enforcedPlatform
para Quarkus BOM
Si nos centramos en la sección de dependencias, se puede ver la extensión que permite el desarrollo de aplicaciones REST:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-rest</artifactId>
</dependency>
implementation("io.quarkus:quarkus-rest")
4.1. The Jakarta REST resources
Durante la creación del proyecto, se ha creado el archivo src/main/java/org/acme/GreetingResource.java
con el siguiente contenido:
package org.acme;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/hello")
public class GreetingResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello from Quarkus REST";
}
}
It’s a very simple REST endpoint, returning "Hello from Quarkus REST" to requests on "/hello".
Differences with vanilla Jakarta REST
With Quarkus, there is no need to create an |
5. Ejecución de la aplicación
Ahora estamos listos para ejecutar nuestra aplicación:
quarkus dev
./mvnw quarkus:dev
./gradlew --console=plain quarkusDev
[INFO] --------------------< org.acme:getting-started >---------------------
[INFO] Building getting-started 1.0.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ getting-started ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory <path>/getting-started/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ getting-started ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 2 source files to <path>/getting-started/target/classes
[INFO]
[INFO] --- quarkus-maven-plugin:<version>:dev (default-cli) @ getting-started ---
Listening for transport dt_socket at address: 5005
2019-02-28 17:05:22,347 INFO [io.qua.dep.QuarkusAugmentor] (main) Beginning quarkus augmentation
2019-02-28 17:05:22,635 INFO [io.qua.dep.QuarkusAugmentor] (main) Quarkus augmentation completed in 288ms
2019-02-28 17:05:22,770 INFO [io.quarkus] (main) Quarkus started in 0.668s. Listening on: http://localhost:8080
2019-02-28 17:05:22,771 INFO [io.quarkus] (main) Installed features: [cdi, rest]
Una vez iniciado, puede usar el endpoint proporcionado:
$ curl -w "\n" http://localhost:8080/hello
Hello from Quarkus REST
Pulsa CTRL+C
para detener la aplicación, o mantenla en funcionamiento y disfruta de la rapidísima recarga en caliente.
Añadir automáticamente una nueva línea con
curl -w "\n" En este ejemplo utilizamos |
6. Uso de la inyección
Dependency injection in Quarkus is based on ArC which is a CDI-based dependency injection solution tailored for Quarkus' architecture. If you’re new to CDI then we recommend you to read the Introduction to CDI guide.
Quarkus sólo implementa un subconjunto de las características de CDI y viene con características no estándar y APIS específicas, puedes aprender más sobre esto en la Guía de contextos e inyección de dependencias.
ArC comes as a dependency of quarkus-rest
so you already have it handy.
Let’s modify the application and add a companion bean.
Create the src/main/java/org/acme/GreetingService.java
file with the following content:
package org.acme;
import jakarta.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class GreetingService {
public String greeting(String name) {
return "hello " + name;
}
}
Edite la clase GreetingResource
para inyectar el GreetingService
y cree un nuevo punto final utilizándolo:
package org.acme;
import jakarta.inject.Inject;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/hello")
public class GreetingResource {
@Inject
GreetingService service;
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/greeting/{name}")
public String greeting(String name) {
return service.greeting(name);
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "Hello from Quarkus REST";
}
}
If you stopped the application (keep in mind you don’t have to do it, changes will be automatically deployed by our live reload feature), restart the application with:
quarkus dev
./mvnw quarkus:dev
./gradlew --console=plain quarkusDev
A continuación, compruebe que el endpoint devuelve hello quarkus
como se esperaba:
$ curl -w "\n" http://localhost:8080/hello/greeting/quarkus
hello quarkus
7. Modo de desarrollo
quarkus:dev
runs Quarkus in development mode. This enables live reload with background compilation, which means
that when you modify your Java files and/or your resource files and refresh your browser, these changes will automatically take effect.
This works too for resource files like the configuration property file.
Refreshing the browser triggers a scan of the workspace, and if any changes are detected, the Java files are recompiled
and the application is redeployed; your request is then serviced by the redeployed application. If there are any issues
with compilation or deployment an error page will let you know.
This will also listen for a debugger on port 5005
. If you want to wait for the debugger to attach before running you
can pass -Dsuspend
on the command line. If you don’t want the debugger at all you can use -Ddebug=false
.
8. Probando
De acuerdo, hasta aquí todo bien, pero no sería mejor con unas cuantas pruebas, por si acaso.
En el archivo de construcción generado, puede ver 2 dependencias de prueba:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-junit5</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
testImplementation("io.quarkus:quarkus-junit5")
testImplementation("io.rest-assured:rest-assured")
Quarkus es compatible con las pruebas de JUnit 5.
Debido a esto, en el caso de Maven, se debe establecer la versión del Surefire Maven Plugin, ya que la versión por defecto no soporta JUnit 5:
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
We also set the java.util.logging
system property to make sure tests will use the correct log manager and maven.home
to ensure that custom configuration
from ${maven.home}/conf/settings.xml
is applied (if any).
The generated project contains a simple test.
Edit the src/test/java/org/acme/GreetingResourceTest.java
to match the following content:
package org.acme;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;
@QuarkusTest
public class GreetingResourceTest {
@Test (1)
public void testHelloEndpoint() {
given()
.when().get("/hello")
.then()
.statusCode(200) (2)
.body(is("Hello from Quarkus REST"));
}
@Test
public void testGreetingEndpoint() {
String uuid = UUID.randomUUID().toString();
given()
.pathParam("name", uuid)
.when().get("/hello/greeting/{name}")
.then()
.statusCode(200)
.body(is("hello " + uuid));
}
}
1 | Utilizando el runner QuarkusTest , se indica a JUnit que inicie la aplicación antes que las pruebas. |
2 | Compruebe el código de estado de la respuesta HTTP y el contenido |
These tests use RestAssured, but feel free to use your favorite library.
Puedes ejecutarlas con Maven:
./mvnw test
También puede ejecutar la prueba desde su IDE directamente (asegúrese de detener la aplicación primero).
By default, tests will run on port 8081
so as not to conflict with the running application. We automatically
configure RestAssured to use this port. If you want to use a different client you should use the @TestHTTPResource
annotation to directly inject the URL of the tested application into a field on the test class. This field can be of the type
String
, URL
or URI
. This annotation can also be given a value for the test path. For example, if I want to test
a Servlet mapped to /myservlet
I would just add the following to my test:
@TestHTTPResource("/myservlet")
URL testUrl;
The test port can be controlled via the quarkus.http.test-port
config property. Quarkus also creates a system
property called test.url
that is set to the base test URL for situations where you cannot use injection.
9. Trabajar con un proyecto multimodal o con módulos externos
Quarkus heavily utilizes Jandex at build time, to discover various classes or annotations. One immediately recognizable application of this, is CDI bean discovery. As a result, most of the Quarkus extensions will not work properly if this build time discovery isn’t properly setup.
Este índice se crea por defecto en el proyecto en el que se configura Quarkus, gracias a nuestros plugins de Maven y Gradle.
However, when working with a multi-module project, be sure to read the Working with multi-module projects
section of the
Maven or Gradle guides.
If you plan to use external modules (for example, an external library for all your domain objects),
you will need to make these modules known to the indexing process either by adding the Jandex plugin (if you can modify them)
or via the quarkus.index-dependency
property inside your application.properties
(useful in cases where you can’t modify the module).
Asegúrese de leer la sección de Bean Discovery de la guía CDI para obtener más información.
10. Empaquetar y ejecutar la aplicación
La aplicación se empaqueta con:
quarkus build
./mvnw install
./gradlew build
Produce varias salidas en /target
:
-
getting-started-1.0.0-SNAPSHOT.jar
- containing just the classes and resources of the projects, it’s the regular artifact produced by the Maven build - it is not the runnable jar; -
the
quarkus-app
directory which contains thequarkus-run.jar
jar file - being an executable jar. Be aware that it’s not an über-jar as the dependencies are copied into subdirectories ofquarkus-app/lib/
.
Puedes ejecutar la aplicación con: java -jar target/quarkus-app/quarkus-run.jar
Si quieres desplegar tu aplicación en algún lugar (normalmente en un contenedor), necesitas desplegar todo el directorio quarkus-app .
|
Antes de ejecutar la aplicación, no olvides detener el modo de recarga en caliente (pulsa CTRL+C ), o tendrás un conflicto de puertos.
|
11. Configuración del banner
By default, when a Quarkus application starts (in regular or dev mode), it will display an ASCII art banner. The banner can be disabled by setting quarkus.banner.enabled=false
in application.properties
,
by setting the -Dquarkus.banner.enabled=false
Java System Property, or by setting the QUARKUS_BANNER_ENABLED
environment variable to false
.
Furthermore, users can supply a custom banner by placing the banner file in src/main/resources
and configuring quarkus.banner.path=name-of-file
in application.properties
.
12. Non Application endpoints
Various Quarkus extensions contribute non-application endpoints that provide different kinds of information about the application. Examples of such extensions are the health, metrics, OpenAPI and info extensions.
These non application endpoints are normally accessible under the /q
prefix like so:
-
/q/health
-
/q/metrics
-
/q/openapi
-
/q/info
but users can also choose to expose one that might present a security risk under a different TCP port using a dedicated management interface.
12.1. Info endpoint
If the application contains the quarkus-info
extension, then Quarkus will by default expose the /q/info
endpoint which provides information about the build, java version, version control, and operating system. The level of detail of the exposed information is configurable.
All CDI beans implementing the InfoContributor
will be picked up and their data will be appended to the endpoint.
12.1.1. Referencia de configuración
Propiedad de configuración fijada en tiempo de compilación - Todas las demás propiedades de configuración son anulables en tiempo de ejecución
Configuration property |
Tipo |
Por defecto |
---|---|---|
Whether the info endpoint will be enabled Environment variable: Show more |
boolean |
|
The path under which the info endpoint will be located Environment variable: Show more |
string |
|
Whether git info will be included in the info endpoint Environment variable: Show more |
boolean |
|
Controls how much information is present in the git section Environment variable: Show more |
|
|
Whether build info will be included in the info endpoint Environment variable: Show more |
boolean |
|
Additional properties to be added to the build section Environment variable: Show more |
Map<String,String> |
|
Whether os info will be included in the info endpoint Environment variable: Show more |
boolean |
|
Whether java info will be included in the info endpoint Environment variable: Show more |
boolean |
|
13. ¿Qué es lo que sigue?
This guide covered the creation of an application using Quarkus. However, there is much more. We recommend continuing the journey by creating your second Quarkus application, with Dev Services and persistence. You can learn about creating a native executable and packaging it in a container with the building a native executable guide. If you are interested in reactive, we recommend the getting started with reactive guide, where you can see how to implement reactive applications with Quarkus.
Además, el documento Guía de herramientas explica cómo:
-
armar un proyecto en una sola línea de comandos
-
activar el modo de desarrollo (recarga en caliente)
-
importar el proyecto en su IDE favorito
-
y más