The English version of quarkus.io is the official project site. Translated sites are community supported on a best-effort basis.
Edit this Page

Criando sua primeira aplicação

In this guide, you’ll create a REST endpoint, see live coding in action, add a service with dependency injection, and write tests. You won’t write any boilerplate, and you won’t have to restart the app, not even once.

Already ran the Quick Start? Skip to Utilizando injeção.

1. Pré-requisitos

Para concluir este guia, você precisa:

  • Cerca de 15 minutos

  • Um IDE

  • JDK 17+ instalado com JAVA_HOME configurado corretamente

  • Apache Maven 3.9.16

  • Opcionalmente, o Quarkus CLI se você quiser usá-lo

Certifique-se de que o Maven está usando a versão do Java que você espera

Se você tiver várias instalações do JDK, pode ser que o Maven não use o Java esperado e você pode acabar obtendo resultados inesperados. Você pode verificar qual JDK o Maven está usando executando o comando mvn —version.

2. Iniciando uma aplicação

A forma mais fácil de criar um novo projeto Quarkus é abrir um terminal e executar o seguinte comando:

CLI
quarkus create app org.acme:getting-started \
    --extension='rest'
cd getting-started

Para criar um projeto Gradle, adicione a opção --gradle ou --gradle-kotlin-dsl.

Para obter mais informações sobre como instalar e usar a CLI do Quarkus, consulte o guia Quarkus CLI.

Maven
mvn io.quarkus.platform:quarkus-maven-plugin:3.37.0:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=getting-started \
    -Dextensions='rest'
cd getting-started

Para criar um projeto Gradle, adicione a opção '-DbuildTool=gradle' ou '-DbuildTool=gradle-kotlin-dsl'.

Para usuários do Windows:

  • Se estiver usando cmd, (não use barra invertida '\' e coloque tudo na mesma linha)

  • Se estiver usando o Powershell, envolva os parâmetros '-D' entre aspas duplas, por exemplo, '"-DprojectArtifactId=getting-started"'

Isso gera o seguinte em `./getting-started:

  • a estrutura Maven

  • an org.acme.GreetingResource REST endpoint exposed on /hello

  • um teste unitário associado

  • uma landing page acessível em http://localhost:8080 depois de iniciar a aplicação

  • exemplo de arquivos Dockerfile para os modos native e jvm em src/main/docker

  • o arquivo de configuração da aplicação

Look at the generated pom.xml. It imports the Quarkus BOM (quarkus-bom), so you can omit the version of Quarkus dependencies in your project. It also uses the quarkus-maven-plugin, which is responsible for packaging the application and providing development mode.

2.1. The REST endpoint

Durante a criação do projeto, o arquivo src/main/java/org/acme/GreetingResource.java foi criado com o seguinte conteúdo:

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".

3. Executando a aplicação

Agora estamos prontos para executar a nossa aplicação:

CLI
quarkus dev
Maven
./mvnw quarkus:dev
Gradle
./gradlew --console=plain quarkusDev
...
__  ____  __  _____   ___  __ ____  ______
 --/ __ \/ / / / _ | / _ \/ //_/ / / / __/
 -/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
INFO  [io.quarkus] (Quarkus Main Thread) getting-started 1.0.0-SNAPSHOT on JVM (powered by Quarkus {quarkus-version}) started in 0.968s. Listening on: http://localhost:8080
INFO  [io.quarkus] (Quarkus Main Thread) Profile dev activated. Live Coding activated.
INFO  [io.quarkus] (Quarkus Main Thread) Installed features: [cdi, rest, smallrye-context-propagation, vertx]

Uma vez iniciado, você pode fazer o request no endpoint fornecido:

$ curl -w "\n" http://localhost:8080/hello
Hello from Quarkus REST

Keep it running and enjoy the blazing fast hot-reload. If you really want shutdown the application, hit CTRL+C.

Adicione automaticamente uma quebra de linha com curl -w “\n”

Estamos usando curl -w “\n” neste exemplo para evitar que seu terminal imprima um ‘%’ ou coloque tanto o resultado quanto o próximo prompt de comando na mesma linha.

4. Live coding

quarkus:dev runs Quarkus in development mode. Edit your Java files or resource files, save, and refresh your browser, changes take effect immediately, no restart needed. If there are any issues with compilation or deployment an error page will let you know.

Try it: open src/main/java/org/acme/GreetingResource.java, change "Hello from Quarkus REST" to "Hola from Quarkus", save, and refresh http://localhost:8080/hello. Then, switch back to "Hello from Quarkus REST", refresh again…​ changed again!

While dev mode is running, open the Dev UI, a dashboard where you can browse installed extensions, configuration, endpoints, and more, all live-updated as you code.

Isso também escutará um depurador na porta 5005 . Se quiser aguardar a conexão do depurador antes de executá-lo, você pode passar -Dsuspend na linha de comando. Se você não quiser o depurador, pode usar -Ddebug=false .

5. Utilizando injeção

A injeção de dependência no Quarkus é baseada no ArC, que é uma solução de injeção de dependência baseada em CDI adaptada à arquitetura do Quarkus. Se você não conhece CDI, recomendamos que leia o guia Introdução ao CDI .

O Quarkus apenas implementa um subconjunto das funcionalidades CDI e inclui funcionalidades não normalizadas e APIS específicos. Você pode obter mais informações sobre este assunto no guia Contexts and Dependency Injection.

ArC comes as a dependency of quarkus-rest so you already have it handy.

Vamos modificar a aplicação e adicionar um companion bean. Crie o arquivo src/main/java/org/acme/GreetingService.java com o seguinte conteúdo:

package org.acme;

import jakarta.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class GreetingService {

    public String greeting(String name) {
        return "hello " + name;
    }

}

Edite a classe GreetingResource para injetar o GreetingService e crie um novo endpoint utilizando-o:

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";
    }
}

Se você parou a aplicação (lembre-se de que não é necessário fazer isso, pois as alterações serão implantadas automaticamente pelo nosso recurso de reload automático), reinicie o aplicativo com:

CLI
quarkus dev
Maven
./mvnw quarkus:dev
Gradle
./gradlew --console=plain quarkusDev

Em seguida, verifique se o endpoint retorna hello quarkus como esperado:

$ curl -w "\n" http://localhost:8080/hello/greeting/quarkus
hello quarkus

6. Testando

All right, so far so good, but wouldn’t it be better with a few tests, just in case?

No arquivo compilado gerado, é possível ver 2 dependências de teste:

pom.xml
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.rest-assured</groupId>
    <artifactId>rest-assured</artifactId>
    <scope>test</scope>
</dependency>
build.gradle
testImplementation("io.quarkus:quarkus-junit")
testImplementation("io.rest-assured:rest-assured")

Quarkus supports JUnit tests.

Because of this, in the case of Maven, the version of the Surefire Maven Plugin must be set, as the default version does not support JUnit:

<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>${surefire-plugin.version}</version>
    <configuration>
       <argLine>--add-opens java.base/java.lang=ALL-UNNAMED</argLine>
       <systemPropertyVariables>
          <java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager>
          <maven.home>${maven.home}</maven.home>
       </systemPropertyVariables>
    </configuration>
</plugin>

Também definimos a propriedade do sistema java.util.logging para garantir que os testes usarão o gerenciador de logs correto e maven.home para garantir que a configuração personalizada de ${maven.home}/conf/settings.xml seja aplicada (se houver).

O projeto gerado contém um teste simples. Edite src/test/java/org/acme/GreetingResourceTest.java para corresponder ao conteúdo a seguir:

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  (1)
class GreetingResourceTest {

    @Test
    void testHelloEndpoint() {
        given()
          .when().get("/hello")
          .then()
             .statusCode(200)    (2)
             .body(is("Hello from Quarkus REST"));
    }

    @Test
    void testGreetingEndpoint() {
        String uuid = UUID.randomUUID().toString();
        given()
          .pathParam("name", uuid)
          .when().get("/hello/greeting/{name}")
          .then()
            .statusCode(200)
            .body(is("hello " + uuid));
    }

}
1 By using the @QuarkusTest annotation, you instruct JUnit to start the application before the tests.
2 Verificar o código de status e o conteúdo da resposta HTTP

Estes testes utilizam o RestAssured, mas sinta-se à vontade para utilizar a sua biblioteca favorita.

Você pode executá-los utilizando o Maven:

./mvnw test

Você também pode executar o teste diretamente a partir do seu IDE (certifique-se de que parou primeiro a aplicação).

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 you want to test an endpoint mapped to /hello, you would just add the following to your @QuarkusTest test:

@TestHTTPResource("/hello")
URL testUrl;

The test port can be controlled via the quarkus.http.test-port config property.

6.1. Continuous testing

You can also have Quarkus run your tests automatically as you code. In the dev mode terminal, press r, and then Quarkus re-runs affected tests on every save, giving you instant feedback without leaving your editor. See the Continuous Testing guide for more details.

7. Empacotando e executando a aplicação

A aplicação é empacotada utilizando:

CLI
quarkus build
Maven
./mvnw install
Gradle
./gradlew build

It produces the quarkus-app directory in /target, which contains the quarkus-run.jar file. This is a fast-jar, not an über-jar, the dependencies are copied into subdirectories of quarkus-app/lib/.

You can run the application using: java -jar target/quarkus-app/quarkus-run.jar.

If you want to deploy your application somewhere (typically in a container), you need to copy/deploy the whole quarkus-app directory.
Antes de executar a aplicação, não se esqueça de parar o modo de recarregamento automático (hot reload) (pressione CTRL+C), ou terá um conflito de portas.

8. E agora, o que vem por aí?

You now have a running Quarkus application with dependency injection and tests. Here’s where to go next:

8.1. Solução

You can find the completed example in the getting-started directory of the Quarkus quickstarts repository:

git clone https://github.com/quarkusio/quarkus-quickstarts.git

Related content