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

Configurar a sua aplicação

The content of this guide and been revised and split into additional topics. Please check the Additional Information section.

Hardcoded values in your code are a no-go (even if we all did it at some point ;-)). In this guide, we will learn how to configure a Quarkus application.

Pré-requisitos

Para concluir este guia, você precisa:

  • Cerca de 15 minutos

  • Um IDE

  • JDK 17+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.9.9

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

  • Opcionalmente, Mandrel ou GraalVM instalado e configurado apropriadamente se você quiser criar um executável nativo (ou Docker se você usar uma compilação de contêiner nativo)

Solução

Recomendamos que siga as instruções nas seções seguintes e crie a aplicação passo a passo. No entanto, você pode ir diretamente para o exemplo completo.

Clone o repositório Git: git clone https://github.com/quarkusio/quarkus-quickstarts.git, ou baixe um arquivo.

The solution is located in the config-quickstart directory.

Crie o projeto Maven

Primeiro, precisamos de um novo projeto. Crie um novo projeto com o seguinte comando:

CLI
quarkus create app org.acme:config-quickstart \
    --extension='rest' \
    --no-code
cd config-quickstart

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.17.4:create \
    -DprojectGroupId=org.acme \
    -DprojectArtifactId=config-quickstart \
    -Dextensions='rest' \
    -DnoCode
cd config-quickstart

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=config-quickstart"'

It generates:

  • a estrutura Maven

  • uma página acessível em http://localhost:8080

  • exemplo de arquivos Dockerfile para os modos nativo e jvm

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

Crie a configuração

A Quarkus application uses the SmallRye Config API to provide all mechanisms related with configuration.

By default, Quarkus reads configuration properties from several sources. For the purpose of this guide, we will use an application configuration file located in src/main/resources/application.properties.

Edit the file with the following content:

application.properties
# Your configuration properties
greeting.message=hello
greeting.name=quarkus

Create a REST resource

Create the org.acme.config.GreetingResource REST resource with the following content:

package org.acme.config;

import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;

@Path("/greeting")
public class GreetingResource {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String hello() {
        return "Hello RESTEasy";
    }
}

Inject the configuration

Quarkus uses MicroProfile Config annotations to inject the configuration properties in the application.

@ConfigProperty(name = "greeting.message") (1)
String message;
1 You can use @Inject @ConfigProperty or just @ConfigProperty. The @Inject annotation is not necessary for members annotated with @ConfigProperty.
If the application attempts to inject a configuration property that is not set, an error is thrown.

Edit the org.acme.config.GreetingResource, and introduce the following configuration properties:

@ConfigProperty(name = "greeting.message") (1)
String message;

@ConfigProperty(name = "greeting.suffix", defaultValue="!") (2)
String suffix;

@ConfigProperty(name = "greeting.name")
Optional<String> name; (3)
1 If you do not provide a value for this property, the application startup fails with jakarta.enterprise.inject.spi.DeploymentException: No config value of type [class java.lang.String] exists for: greeting.message.
2 The default value is injected if the configuration does not provide a value for greeting.suffix.
3 This property is optional - an empty Optional is injected if the configuration does not provide a value for greeting.name.

Now, modify the hello method to use the injected properties:

@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
    return message + " " + name.orElse("world") + suffix;
}
Use @io.smallrye.config.ConfigMapping annotation to group multiple configurations in a single interface. Please, check the Config Mappings documentation.

Store secrets in an environment properties file

A secret (such as a password, a personal access token or an API key) must not end up in version control for security reasons. One way is to store them in a local environment properties (.env) file:

  1. Store the secret in the .env file in the project root directory.

    The .env file
    foo.api-key=ThisIsSecret
  2. Add the .env file to .gitignore.

mvn quarkus:dev automatically picks up the properties in the .env file, similar to those in the application.properties file.

Atualize o teste

We also need to update the functional test to reflect the changes made to the endpoint. Create the src/test/java/org/acme/config/GreetingResourceTest.java file with the following content:

package org.acme.config;

import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.CoreMatchers.is;

@QuarkusTest
public class GreetingResourceTest {

    @Test
    public void testHelloEndpoint() {
        given()
          .when().get("/greeting")
          .then()
             .statusCode(200)
             .body(is("hello quarkus!")); // Modified line
    }

}

Empacote e execute a aplicação

Execute a aplicação com:

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

Abra o seu navegador em http://localhost:8080/greeting .

Changing the configuration file is immediately reflected. You can add the greeting.suffix, remove the other properties, change the values, etc.

Como de costume, a aplicação pode ser empacotada utilizando:

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

and executed using java -jar target/quarkus-app/quarkus-run.jar.

Também é possível gerar o executável nativo com:

CLI
quarkus build --native
Maven
./mvnw install -Dnative
Gradle
./gradlew build -Dquarkus.native.enabled=true

Programmatically access the configuration

The org.eclipse.microprofile.config.ConfigProvider.getConfig() API allows to access the Config API programmatically. This API is mostly useful in situations where CDI injection is not available.

String databaseName = ConfigProvider.getConfig().getValue("database.name", String.class);
Optional<String> maybeDatabaseName = ConfigProvider.getConfig().getOptionalValue("database.name", String.class);

Configuring Quarkus

Quarkus itself is configured via the same mechanism as your application. Quarkus reserves the quarkus. namespace for its own configuration. For example to configure the HTTP server port you can set quarkus.http.port in application.properties. All the Quarkus configuration properties are documented and searchable.

As mentioned above, properties prefixed with quarkus. are effectively reserved for configuring Quarkus itself and its extensions. Therefore, the quarkus. prefix should never be used for application specific properties.

Build Time configuration

Some Quarkus configurations only take effect during build time, meaning is not possible to change them at runtime. These configurations are still available at runtime but as read-only and have no effect in Quarkus behaviour. A change to any of these configurations requires a rebuild of the application itself to reflect changes of such properties.

The properties fixed at build time are marked with a lock icon () in the list of all configuration options.

However, some extensions do define properties overridable at runtime. A simple example is the database URL, username and password which is only known specifically in your target environment, so they can be set and influence the application behaviour at runtime.

Additional Information

Quarkus relies on SmallRye Config and inherits its features:

  • Additional ConfigSources

  • Additional Converters

  • Indexed properties

  • Parent profile

  • Interceptors for configuration value resolution

  • Relocate configuration properties

  • Fallback configuration properties

  • Registrando

  • Hide secrets

For more information, please check the SmallRye Config documentation.

Conteúdo Relacionado