Configuration Reference Guide

本指南的内容已进行修订并拆分为其他多个主题。请查看 Additional Information 小节。

The content of this guide has been revised and split into additional topics. Please check the additional-information section.

在本参考指南中,我们将描述 Quarkus 配置的各个方面。Quarkus 应用程序和 Quarkus 本身(核心和扩展)都是通过相同的机制进行配置的,该机制利用 SmallRye Config API(实现 MicroProfile Config 规范)。

In this reference guide we’re going to describe various aspects of Quarkus configuration. A Quarkus application and Quarkus itself (core and extensions) are both configured via the same mechanism that leverages the SmallRye Config API an implementation of the MicroProfile Config specification.

如果您正在寻找有关如何使 Quarkus 扩展可配置的信息,请参阅 Writing Your Own Extension 指南。

If you’re looking for information how to make a Quarkus extension configurable then see the Writing Your Own Extension guide.

Config Sources

默认情况下,Quarkus 从多个来源读取配置属性(按降序排列):

By default, Quarkus reads configuration properties from multiple sources (by descending ordinal):

  1. (400) system-properties

  2. (300) environment-variables

  3. (295) env-file file in the current working directory

  4. (260) application-properties-file in $PWD/config/application.properties

  5. (250) application-properties-file application.properties in classpath

  6. (100) microprofile-config-properties-file META-INF/microprofile-config.properties in classpath

最终配置是所有这些来源定义的属性的聚合。配置属性查找从可用的最高序号配置源开始,然后一直向下到其他来源,直到找到匹配项。这意味着任何配置属性都可以仅通过在较高序号配置源中设置不同的值来覆盖该值。例如,使用环境属性配置的属性将覆盖使用 application.properties 文件提供的属性。

The final configuration is the aggregation of the properties defined by all these sources. A configuration property lookup starts by the highest ordinal configuration source available and works it way down to other sources until a match is found. This means that any configuration property may override a value just by setting a different value in a higher ordinal config source. For example, a property configured using an environment property overrides the value provided using the application.properties file.

config sources

System properties

系统属性可以在启动期间通过 -D 标志传递给应用程序。以下示例将值 youshallnotpass 分配给属性 quarkus.datasource.password

System properties can be handed to the application through the -D flag during startup. The following examples assign the value youshallnotpass to the attribute quarkus.datasource.password.

  • For Quarkus dev mode: ./mvnw quarkus:dev -Dquarkus.datasource.password=youshallnotpass

  • For a runner jar: java -Dquarkus.datasource.password=youshallnotpass -jar target/quarkus-app/quarkus-run.jar

  • For a native executable: ./target/myapp-runner -Dquarkus.datasource.password=youshallnotpass

Environment variables

  • For a runner jar: export QUARKUS_DATASOURCE_PASSWORD=youshallnotpass ; java -jar target/quarkus-app/quarkus-run.jar

  • For a native executable: export QUARKUS_DATASOURCE_PASSWORD=youshallnotpass ; ./target/myapp-runner

环境变量名称遵循 MicroProfile Config 指定的转换规则。Config 为给定的属性名称(例如 foo.BAR.baz)搜索三个环境变量:

Environment variables names follow the conversion rules specified by MicroProfile Config. Config searches three environment variables for a given property name (e.g. foo.BAR.baz):

  • foo.BAR.baz - Exact match

  • foo_BAR_baz - Replace each character that is neither alphanumeric nor with

  • FOO_BAR_BAZ - Replace each character that is neither alphanumeric nor with ; then convert the name to upper case

SmallRye Config 指定 additional conversion rules

SmallRye Config specifies additional conversion rules.

  • A property with double quotes foo."bar".baz, replace each character that is neither alphanumeric nor with : FOOBARBAZ

  • A property with dashes foo.bar-baz, replace each character that is neither alphanumeric nor with : FOO_BAR_BAZ

  • An indexed property foo.bar[0] or foo.bar[0].baz, replace each character that is neither alphanumeric nor with : FOO_BAR_0_ or FOO_BAR_0__BAZ

在某些情况下,查找精确的属性名称是不可能的。这是对于包含用户定义路径段的配置名称来说的情况。

In some situations, looking up the exact property name is impossible. This is the case for configuration names that contain user defined path segments.

应用环境变量名称的转换规则,quarkus.datasource."datasource-name".jdbc.url 变成了 QUARKUS_DATASOURCEDATASOURCE_NAMEJDBC_URL。如果这两个属性都可在 Config 系统中使用,该配置将按预期返回结果。

Applying the conversion rules for Environment Variables names, quarkus.datasource."datasource-name".jdbc.url becomes QUARKUS_DATASOURCEDATASOURCE_NAMEJDBC_URL. The configuration will work as expected if both properties are available in the Config system.

如果只有 QUARKUS_DATASOURCEDATASOURCE_NAMEJDBC_URL (存在),Config 系统需要将该配置名称重新转换为其最可能的带点的格式。对固定的配置段来说这样很好,但对包含动态段的名称来说不行。在此情况下,Quarkus 无法确定 DATASOURCE_NAME 应当转换为 datasource.name 还是 datasource-name (或任何其他特殊字符分隔符)。

If only QUARKUS_DATASOURCEDATASOURCE_NAMEJDBC_URL is present, the Config system needs to reconvert the configuration name to its most likely dotted format. This works fine for fixed configuration segments, but not for names that contain dynamic segments. In this case, Quarkus is unable to determine if DATASOURCE_NAME should be converted to datasource.name or datasource-name (or any other special character separator).

出于此原因,此类属性总要求其点分版本名称在另一个源中(值可以留空)以消除环境变量名称歧义。它将提供额外的信息来执行双向转换,并将属性名称匹配在一起。

For this reason, such properties always require their dotted version name in another source (the value can be left empty) to disambiguate the Environment Variable name. It will provide additional information to perform a two-way conversion and match the property names together.

# value can be left empty
quarkus.datasource."datasource-name".jdbc.url=
EXPORT QUARKUS_DATASOURCE__DATASOURCE_NAME__JDBC_URL=jdbc:postgresql://localhost:5432/database

.env file in the current working directory

.env
QUARKUS_DATASOURCE_PASSWORD=youshallnotpass 1
1 The name QUARKUS_DATASOURCE_PASSWORD follows the same conversion rules used for Environment variables.

对于 dev 模式,该文件可以放在项目的根中,但建议将其检查到 not 版本控制中,因为它通常包含密码、访问令牌、API 密钥或其他机密。

For dev mode, this file can be placed in the root of the project, but it is advised to not check it in to version control because it typically contains passwords, access tokens, API keys or other secrets.

.env 文件中的环境变量无法通过 System.getenv(String) API 使用。

Environment variables in the .env file are not available via the System.getenv(String) API.

Quarkus Application configuration file

Quarkus 应用程序配置文件从类路径资源中加载,例如 src/main/resources/application.propertiessrc/test/resources/application.properties 或从一个 jar 依赖项中(包含一个 application.properties 项)。发现的每个 application.properties 都被视为一个单独的 ConfigSource,并遵循与任何其他源一样的规则(按属性覆盖)。另外,配置文件也 $PWD/config/application.properties 驻留。从配置文件夹中开始加载,然后再是类路径顺序(application.properties 文件在应用程序源中在类加载器加载顺序中具有优先级)。

The Quarkus Application configuration file is loaded from the classpath resources, for instance src/main/resources/application.properties, src/test/resources/application.properties or from a jar dependency that contains an application.properties entry. Each application.properties found is treated as a separate ConfigSource and follow the same rules as every other source (override per property). Additionally, the configuration file may also reside in $PWD/config/application.properties. The loading starts from the config folder and then classpath order (application.properties files in the application sources will have priority on the classloader loading order).

application.properties
greeting.message=hello 1
quarkus.http.port=9090 2
1 This is a user-defined configuration property.
2 This is a configuration property consumed by the quarkus-vertx-http extension.

config/application.properties 也可用于 dev 模式。该文件需要放在构建工具输出目录中(Maven 的 target 和 Gradle 的 build/classes/java/main)。但是,请注意,来自构建工具的任何清理操作,如 mvn cleangradle clean,都会同时删除 config 目录。

The config/application.properties is also available in dev mode. The file needs to be placed inside the build tool output directory (target for Maven and build/classes/java/main for Gradle). Keep in mind however that any cleaning operation from the build tool like mvn clean or gradle clean will remove the config directory as well.

MicroProfile Config configuration file

src/main/resources/META-INF/microprofile-config.properties 中的 MicroProfile Config 配置文件。

The MicroProfile Config configuration file in src/main/resources/META-INF/microprofile-config.properties.

microprofile-config.properties
greeting.message=hello 1
quarkus.http.port=9090 2
1 This is a user-defined configuration property.
2 This is a configuration property consumed by the quarkus-vertx-http extension.

它以与 Quarkus 应用程序配置文件 application.properties 完全相同的方式工作。建议使用 Quarkus application.properties

It works in the exact same way as Quarkus Application configuration file application.properties. Recommendation is to use Quarkus application.properties.

Locations

除了默认配置位置外,Quarkus 还提供一种扫描配置文件的其他位置的方法。

Additionally to the default config locations, Quarkus provides a way to scan additional locations for configuration properties files.

quarkus.config.locations`配置属性接受多个由逗号分隔的位置,,且每个都必须表示有效的 `URI。受支持的 `URI`架构包括:

The quarkus.config.locations configuration property accepts multiple locations separated by a comma , and each must represent a valid URI. The supported URI schemes are:

  • file or directory (file:)

  • classpath resource

  • jar resource (jar:)

  • http resource (http:)

所有已加载源都使用找到 quarkus.config.locations`配置属性的源的相同序数。例如,如果 `quarkus.config.locations`被设定为系统属性,那么所有已加载的源都可以将其序数设定为 `400(系统属性使用 `400`作为其序数)。可以通过设置 `config_ordinal`属性和序数值来直接覆盖每个配置源的序数。`config_ordinal`属性只影响其中被设置的源的序数。源首先按其序数排序,然后按位置顺序排序,最后按加载顺序排序。

All loaded sources use the same ordinal of the source that found the quarkus.config.locations configuration property. For instance, if quarkus.config.locations is set as a system property, then all loaded sources have their ordinals set to 400 (system properties use 400 as their ordinal). The ordinal may be overridden directly for each config source by setting the config_ordinal property and the ordinal value. The config_ordinal property only affects the ordinal of the source in which is being set. Sources are sorted first by their ordinal, then by location order, and finally by loading order.

Additional Config Sources

Quarkus 提供的其他扩展覆盖了其他配置格式和存储:

Quarkus provides additional extensions which cover other configuration formats and stores:

创建 Custom Config Source也是可能的。

It is also possible to create a Custom Config Source.

Inject

Quarkus 使用 MicroProfile Config 注释,向应用程序中注入配置属性。

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.

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

使用 Config Mappings对相似的配置属性进行分组。

Use Config Mappings to group similar configuration properties.

Default Values

如果某个属性与默认值(通过 defaultValue`属性)相关联,并且没有为该属性提供配置值,那么不会抛出 `jakarta.enterprise.inject.spi.DeploymentException,而是将使用默认值。defaultValue`值表示为 `String,并使用与处理配置值相同的转换机制。内置转换器已经存在很多用于基元、装箱基元和其他类的转换器;例如:

If a property is associated with a default value (by way of the defaultValue attribute), and no configuration value is supplied for the property, then rather than throwing a jakarta.enterprise.inject.spi.DeploymentException, the default value will be used. The defaultValue value is expressed as a String, and uses the same conversion mechanism used to process configuration values. Several Built-in Converters already exist for primitives, boxed primitives, and other classes; for example:

  • Primitives: boolean, byte, short, etc.

  • Boxed primitives: java.lang.Boolean, java.lang.Byte, java.lang.Short, etc.

  • Optional containers: java.util.Optional, java.util.OptionalInt, java.util.OptionalLong, and java.util.OptionalDouble

  • Java enum types

  • JSR 310 java.time.Duration

  • JDK networking java.net.SocketAddress, java.net.InetAddress, etc.

正如您所料,这些转换器都是 `org.eclipse.microprofile.config.spi.Converter`实现。因此,这些转换器符合 Microprofile 或自定义实现提供程序表达规则,如下所示:

As you might expect, these converters are org.eclipse.microprofile.config.spi.Converter implementations. Therefore, these converters comply with the Microprofile or custom implementation providers expression rules like:

  • Boolean values will be true in cases "true", "1", "YES", "Y" "ON". Otherwise, value will be interpreted as false

  • For float and double values the fractional digits must be separated by a dot .

请注意,当 `Optional*`类型和 `defaultValue`属性的组合使用时,已定义的 `defaultValue`仍将被使用,并且如果没有为属性指定值,则 `Optional*`将存在并填入转换后的默认值。但是,当该属性明确为空时,则不使用默认值并且 `Optional`将为空。考虑以下示例:

Note that when a combination of Optional* types and the defaultValue attribute are used, the defined defaultValue will still be used and if no value is given for the property, the Optional* will be present and populated with the converted default value. However, when the property is explicitly empty, the default value is not used and the Optional will be empty. Consider this example:

# missing value, optional property
greeting.name=

在这种情况下,由于在上面已将 greeting.name`配置为 `Optional*,因此相应的属性值将为空的 Optional,并且执行将正常继续。即使存在已配置的默认值,情况也是如此:如果在配置中明确清除了该属性,则使用该默认值 not

In this case, since greeting.name was configured to be Optional* up above, the corresponding property value will be an empty Optional and execution will continue normally. This would be the case even if there was a default value configured: the default value is not used if the property is explicitly cleared in the configuration.

另一方面,此示例:

On the other hand, this example:

# missing value, non-optional
greeting.suffix=

将在启动时导致 `java.util.NoSuchElementException: SRCFG02004: Required property greeting.message not found`并且不会分配默认值。

will result in a java.util.NoSuchElementException: SRCFG02004: Required property greeting.message not found on startup and the default value will not be assigned.

以下是 Quarkus 提供的转换器的示例:

Below is an example of a Quarkus-supplied converter:

@ConfigProperty(name = "server.address", defaultValue = "192.168.1.1")
InetAddress serverAddress;

Programmatically access

org.eclipse.microprofile.config.ConfigProvider.getConfig() API 允许以编程方式访问配置 API。此 API 主要在 CDI 注入不可用的情况下有用。

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);

不要使用 `System.getProperty(String)`或 `System.getEnv(String)`来检索配置值。这些 API 不了解配置,并且不支持本指南中描述的功能。

Do not use System.getProperty(String) or System.getEnv(String) to retrieve configuration values. These APIs are not configuration aware and do not support the features described in this guide.

Profiles

我们经常需要根据目标_environment_来不同地配置应用程序。例如,本地开发环境可能不同于生产环境。

We often need to configure our application differently depending on the target environment. For example, the local development environment may be different from the production environment.

配置文件允许在同一文件中或单独的文件中进行多个配置,并通过配置文件名在它们之间进行选择。

Configuration Profiles allow for multiple configurations in the same file or separate files and select between them via a profile name.

Profile in the property name

为了能够设置具有相同名称的属性,每个属性需要使用百分比符号 % 加上配置文件名和一个点 . 作为前缀,语法如下 %{profile-name}.config.name

To be able to set properties with the same name, each property needs to be prefixed with a percentage sign % followed by the profile name and a dot . in the syntax %{profile-name}.config.name:

application.properties
quarkus.http.port=9090
%dev.quarkus.http.port=8181

Quarkus 的 HTTP 端口为 9090。如果 dev 的配置文件处于启用状态,则为 8181。

The Quarkus HTTP port will be 9090. If the dev profile is active it will be 8181.

.env 文件中的配置文件遵循语法 _{PROFILE}_CONFIG_KEY=value

Profiles in the .env file follow the syntax _{PROFILE}_CONFIG_KEY=value:

.env
QUARKUS_HTTP_PORT=9090
_DEV_QUARKUS_HTTP_PORT=8181

如果某个配置文件未为特定属性定义值,则会使用 default (无配置文件)的值:

If a profile does not define a value for a specific attribute, the default (no profile) value is used:

application.properties
bar=”hello”
baz=”bonjour”
%dev.bar=”hallo”

dev 配置文件启用时,属性 bar 的值为 hallo,但属性 baz 的值为 bonjour。如果 prod 配置文件启用,则 bar 的值为 hello(因为没有针对 prod 配置文件的具体值),而 baz 的值为 bonjour

With the dev profile enabled, the property bar has the value hallo, but the property baz has the value bonjour. If the prod profile is enabled, bar has the value hello (as there is no specific value for the prod profile), and baz the value bonjour.

Default Profiles

默认情况下,Quarkus 提供三个配置文件,它们会在特定条件下自动激活:

By default, Quarkus provides three profiles, that activate automatically in certain conditions:

  • dev - Activated when in development mode (i.e. quarkus:dev)

  • test - Activated when running tests

  • prod - The default profile when not running in development or test mode

Custom Profiles

还可以创建其他配置文件,并使用 quarkus.profile 配置属性来激活它们。唯一的要求是使用新配置文件名称设置单个配置属性:

It is also possible to create additional profiles and activate them with the quarkus.profile configuration property. A single config property with the new profile name is the only requirement:

application.properties
quarkus.http.port=9090
%staging.quarkus.http.port=9999

quarkus.profile 设置为 staging 将激活 staging 配置文件。

Setting quarkus.profile to staging will activate the staging profile.

io.smallrye.config.SmallRyeConfig#getProfiles API 提供了一种以编程方式检索活动配置文件的方法。

The io.smallrye.config.SmallRyeConfig#getProfiles API provides a way to retrieve the active profiles programmatically.

Profile aware files

在这种情况下,特定配置文件的属性可能驻留在名为 application-{profile}.properties 的文件中。先前的示例可以表示为:

In this case, properties for a specific profile may reside in an application-{profile}.properties named file. The previous example may be expressed as:

application.properties
quarkus.http.port=9090
%staging.quarkus.http.test-port=9091
application-staging.properties
quarkus.http.port=9190
quarkus.http.test-port=9191

在这种样式中,配置文件感知文件中的配置名称不需要以配置文件名称为前缀。

In this style, the configuration names in the profile aware file do not need to be prefixed with the profile name.

配置文件感知文件中的属性优先于主文件中定义的配置文件感知属性。

Properties in the profile aware file have priority over profile aware properties defined in the main file.

不要使用配置文件感知文件来设置 quarkus.profilequarkus.test.profile。这不起作用,因为配置文件在加载配置文件感知文件之前是必需的。

Do not use profile aware files to set quarkus.profile or quarkus.test.profile. This will not work because the profile is required in advance to load the profile aware files.

仅当未生成配置文件的“@ [1]” 也在同一位置可用,并且文件扩展名在这些文件之间匹配时,才会加载配置文件感知文件。这样做是为了保持一致的加载顺序,并将所有一起配对资源。

A profile aware file is only loaded if the unprofiled application.properties is also available in the same location and the file extension matches between the files. This is required to keep a consistent loading order and pair all the resources together.

Parent Profile

父配置文件为当前配置文件添加一个级别的层次结构。配置 “@ [5]” 接受一个个人配置文件名称。

A Parent Profile adds one level of hierarchy to the current profile. The configuration quarkus.config.profile.parent accepts a single profile name.

在父配置文件处于活动状态时,如果在当前活动配置文件中找不到属性,则配置查找会降级为父配置文件。考虑:

When the Parent Profile is active, if a property cannot be found in the current active Profile, the config lookup fallbacks to the Parent Profile. Consider:

quarkus.profile=dev
quarkus.config.profile.parent=common

%common.quarkus.http.port=9090
%dev.quarkus.http.ssl-port=9443

quarkus.http.port=8080
quarkus.http.ssl-port=8443

然后

Then

  • The active profile is dev

  • The parent profile is common

  • quarkus.http.port is 9090

  • quarkus.http.ssl-port is 9443

不要使用配置文件感知文件来设置 “@ [8]”。这将不起作用,因为提前需要配置文件才能加载配置文件感知文件。

Do not use Profile aware files to set quarkus.config.profile.parent. This will not work because the profile is required in advance to load the profile aware files.

Multiple Profiles

多个配置文件可以同时处于活动状态。配置 “@ [9]” 接受以逗号分隔的个人配置文件名称列表: “@ [10]”。“@ [11]” 和 “@ [12]” 都是单独的个人配置文件。

Multiple Profiles may be active at the same time. The configuration quarkus.profile accepts a comma-separated list of profile names: quarkus.profile=common,dev. Both common and dev are separate profiles.

当多个配置文件处于活动状态时,配置文件配置的规则是相同的。如果两个配置文件定义相同的配置,则最后列出的配置文件具有优先权。考虑:

When multiple profiles are active, the rules for profile configuration are the same. If two profiles define the same configuration, then the last listed profile has priority. Consider:

application.properties
quarkus.profile=common,dev

my.prop=1234
%common.my.prop=1234
%dev.my.prop=5678

%common.commom.prop=common
%dev.dev.prop=dev
%test.test.prop=test

然后

Then

  • common.prop value is common

  • dev.prop value is dev

  • my.prop value is 5678

  • test.prop does not have a value

还可以使用以逗号分隔的个人配置文件名称列表定义多个配置文件属性。如果相同的属性名称存在于多个配置文件属性中,则具有最特定配置文件的属性名称获胜:

It is also possible to define multiple profile properties, with a comma-separated list of profile names. If the same property name exists in multiple profile properties then, the property name with the most specific profile wins:

application.properties
quarkus.profile=dev

%prod,dev.my.prop=1234
%dev.my.prop=5678

%prod,dev.another.prop=1234

然后

Then

  • my.prop value is 5678.

  • another.prop value is 1234.

多个配置文件的优先级按相反的顺序处理。“@ [15]”,Quarkus 首先检查 “@ [16]” 个人配置文件,然后检查 “@ [17]” 个人配置文件。

Multiple profiles priority work in reverse order. With quarkus.profile=common,dev, Quarkus first checks the dev profile and then the common profile.

Default Runtime Profile

Quarkus 运行时个人配置文件默认为用于构建应用程序的个人配置文件:

The default Quarkus runtime profile is set to the profile used to build the application:

./mvnw package -Dnative -Dquarkus.profile=prod-aws
./target/my-app-1.0-runner (1)
1 The command will run with the prod-aws profile. This can be overridden using the quarkus.profile configuration.

Property Expressions

Quarkus 在配置值上提供属性表达式扩展。表达式字符串是纯字符串和表达式片段的混合,由序列 “@ [20]” 包装。

Quarkus provides property expressions expansion on configuration values. An expression string is a mix of plain strings and expression segments, which are wrapped by the sequence ${ …​ }.

在读取属性时解析这些表达式。因此,如果配置属性是构建时间,则属性表达式将在构建时解析。如果可以在运行时覆盖配置属性,则将在运行时解析它。

These expressions are resolved when the property is read. So if the configuration property is build time the property expression will be resolved at build time. If the configuration property is overridable at runtime it will be resolved at runtime.

考虑:

Consider:

application.properties
remote.host=quarkus.io
callable.url=https://${remote.host}/

“@ [21]” 属性的解析值是 “@ [22]”。

The resolved value of the callable.url property is https://quarkus.io/.

另一个示例是按配置文件定义不同的数据库服务器:

Another example would be defining different database servers by profile:

application.properties
%dev.quarkus.datasource.jdbc.url=jdbc:mysql://localhost:3306/mydatabase?useSSL=false
quarkus.datasource.jdbc.url=jdbc:mysql://remotehost:3306/mydatabase?useSSL=false

简化后为:

can be simplified to:

application.properties
%dev.application.server=localhost
application.server=remotehost

quarkus.datasource.jdbc.url=jdbc:mysql://${application.server}:3306/mydatabase?useSSL=false

此外,“表达式扩展”引擎支持以下部分:

Additionally, the Expression Expansion engine supports the following segments:

  • ${expression:value} - Provides a default value after the : if the expansion doesn’t find a value.

  • ${my.prop${compose}} - Composed expressions. Inner expressions are resolved first.

  • ${my.prop}${my.prop} - Multiple expressions.

如果无法扩展表达式且未提供默认值,则会抛出 NoSuchElementException

If an expression cannot be expanded and no default is supplied a NoSuchElementException is thrown.

在所有配置源中执行表达式查找。表达式值和扩展值可能位于不同的配置源中。

Expressions lookups are performed in all config sources. The expression values and expansion values may reside in different config sources.

With Environment Variables

属性表达式也可与环境变量配合使用。

Property Expressions also work with Environment Variables.

application.properties
remote.host=quarkus.io
application.host=${HOST:${remote.host}}

这将扩展 HOST 环境变量,并将属性 remote.host 的值用作默认值,如果未设置 HOST

This will expand the HOST environment variable and use the value of the property remote.host as the default value if HOST is not set.

Secret Keys Expressions

机密配置可表示为 ${handler::value},其中 handler 是用于对 value 进行解码或解密的 io.smallrye.config.SecretKeysHandler 的名称。请考虑:

A secret configuration may be expressed as ${handler::value}, where the handler is the name of a io.smallrye.config.SecretKeysHandler to decode or decrypt the value. Consider:

application.properties
my.secret=${aes-gcm-nopadding::DJNrZ6LfpupFv6QbXyXhvzD8eVDnDa_kTliQBpuzTobDZxlg}

# the encryption key required to decode the secret. It can be set in any source.
smallrye.config.secret-handler.aes-gcm-nopadding.encryption-key=somearbitrarycrazystringthatdoesnotmatter

查找 my.secret 将使用 SecretKeysHandler 名称 aes-gcm-nopadding 对值 DJNrZ6LfpupFv6QbXyXhvzD8eVDnDa_kTliQBpuzTobDZxlg 进行解码。

A lookup to my.secret will use the SecretKeysHandler name aes-gcm-nopadding to decode the value DJNrZ6LfpupFv6QbXyXhvzD8eVDnDa_kTliQBpuzTobDZxlg.

如需了解更多信息,请查看 SmallRye 配置 Secret Keys 文档。

For more information, please check SmallRye Config Secret Keys documentation.

SmallRye 配置可能会提供 Quarkus 完全不支持的处理程序。当前,仅支持 smallrye-config-crypto

SmallRye Config may provide handlers not fully supported by Quarkus. Currently, only smallrye-config-crypto is supported.

Accessing a generating UUID

Quarkus 的默认配置源提供随机的 UUID 值。它在启动时生成 UUID。因此,值在启动(包括开发模式中的重新加载)之间发生变化。

The default config source from Quarkus provides a random UUID value. It generates the UUID at startup time. So, the value changes between startups, including reloads in dev mode.

可以使用 quarkus.uuid 属性访问生成的值。使用 expressions 访问它: ${quarkus.uuid}。例如,它可用于使用唯一消费者组配置 Kafka 客户端:

You can access the generated value using the quarkus.uuid property. Use property-expressions to access it: ${quarkus.uuid}. For example, it can be useful to configure a Kafka client with a unique consumer group:

mp.messaging.incoming.prices.group.id=${quarkus.uuid}

Clearing properties

可选的运行时属性,且在构建时或具有默认值时已设置了值,可以通过向属性分配一个空字符串来明确清除。请注意,这将影响运行时属性,并且与不需要其值属性一起使用时不适用。

Run time properties which are optional, and which have had values set at build time or which have a default value, may be explicitly cleared by assigning an empty string to the property. Note that this will only affect runtime properties, and will only work with properties whose values are not required.

application.properties
remote.host=quarkus.io

使用 -Dremote.host= 查找 remote.host 时将抛出异常,因为系统属性已清除该值。

A lookup to remote.host with -Dremote.host= will throw an Exception, because the system property cleared the value.

Indexed Properties

包含未转义逗号的配置值可以转换为 Collection。这适用于简单的情况,但对于更高级的情况来说,它会变得繁琐且受限。

A config value which contains unescaped commas may be converted to Collection. This works for simple cases, but it becomes cumbersome and limited for more advanced cases.

索引属性提供了一种在配置属性名称中使用索引的方法,以映射 Collection 类型中的特定元素。由于索引元素是属性名称的一部分,不包含在值中,因此也可将其用于映射复杂的对象类型,如 Collection 元素。请考虑:

Indexed Properties provide a way to use indexes in config property names to map specific elements in a Collection type. Since the indexed element is part of the property name and not contained in the value, this can also be used to map complex object types as Collection elements. Consider:

application.properties
my.collection=dog,cat,turtle

my.indexed.collection[0]=dog
my.indexed.collection[1]=cat
my.indexed.collection[2]=turtle

索引属性语法使用属性名称和带有索引的中括号 [ ]

The indexed property syntax uses the property name and square brackets `[ ] with an index in between.

调用 Config#getValues("my.collection", String.class) 时,将自动创建和转换 List<String>,其中包含 dogcatturtle 等值。调用 Config#getValues("my.indexed.collection", String.class) 会返回完全相同的结果。如果同一属性名称同时存在于常规形式和索引形式中,则常规值具有优先级。

A call to Config#getValues("my.collection", String.class), will automatically create and convert a List<String> that contains the values dog, cat and turtle. A call to Config#getValues("my.indexed.collection", String.class) returns the exact same result. If the same property name exists in both forms (regular and indexed), the regular value has priority.

在添加到目标 Collection`之前,会根据索引对索引属性进行排序。索引中包含的任何间隙都不会解析为目标 `Collection,这意味着 Collection 结果将存储所有值,没有任何间隙。

The indexed property is sorted by their index before being added to the target Collection. Any gaps contained in the indexes do not resolve to the target Collection, which means that the Collection result will store all values without any gaps.

Configuring Quarkus

Quarkus 本身使用与应用程序相同的机制进行配置。Quarkus 保留 quarkus. 命名空间用于自身配置。例如,要配置 HTTP 服务器端口,您可以在 application.properties 中设置 quarkus.http.port。所有 Quarkus 配置属性都是 documented and searchable

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.

如上所述,以 quarkus. 为前缀的属性实际上是保留用于配置 Quarkus 本身及其扩展的。因此,quarkus. 前缀应该 never 用于应用程序特定属性。

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

某些 Quarkus 配置只在构建时生效,这意味着在运行时无法更改它们。这些配置在运行时仍然可用,但只读且不会影响 Quarkus 行为。要更改任何这些配置,需要重新构建应用程序本身以反映这些属性的更改。

Some Quarkus configurations only take effect during build time, meaning it 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.

构建时固定的属性会在 list of all configuration options 中用锁图标 () 标记。

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

但是,一些扩展确实定义了属性 overridable at runtime。一个简单的例子是数据库 URL、用户名和密码,这些通常只在您的目标环境中知道,因此可以在运行时设置它们并影响应用程序的行为。

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.

Change build time properties after your application has been published

如果您在应用程序构建后需要更改构建时间配置,则查看如何使用 re-augmentation 为不同的构建时间配置重建增强输出。

If you are in the rare situation that you need to change the build time configuration after your application is built, then check out how re-augmentation can be used to rebuild the augmentation output for a different build time configuration.

Tracking effective build time configuration used at build time

考虑到配置源通常提供的选项多于实际在构建期间使用的选项,了解在 Quarkus 构建过程中实际使用了哪些配置选项可能非常有用。

Given that configuration sources usually provide more options than actually used during the build, it might be useful to know which configuration options have actually been used during a Quarkus build process.

Dumping build time configuration options read during the build

quarkus.config-tracking.enabled 设置为 `true`将启用一个配置拦截器,该拦截器将记录在构建过程中读取的每个配置选项和它们的值。生成的报告将默认存储在 `${project.basedir}/.quarkus/quarkus-prod-config-dump`中。可以通过以下选项配置目标文件:

Setting quarkus.config-tracking.enabled to true will enable a configuration interceptor that will record every configuration option that was read during the build process along with their values. The resulting report will be stored in ${project.basedir}/.quarkus/quarkus-prod-config-dump by default. The target file could be configured using the following options:

  • quarkus.config-tracking.directory - directory in which the configuration dump should be stored, the default is ${project.basedir}/.quarkus

  • quarkus.config-tracking.file-prefix - file name prefix, the default value is quarkus

  • quarkus.config-tracking.file-suffix - file name suffix, the default value is -config-dump

  • quarkus.config-tracking.file - path to a file in which the configuration dump should be stored. This option supersedes the file-prefix and file-suffix options. Also supersedes the value of quarkus.config-tracking.directory, unless the value is a relative path.

quarkus-prod-config-dump 文件名中的 prod 部分指的是 Quarkus 构建模式,表示已为生产构建进行了转储。

The prod part of the quarkus-prod-config-dump file name refers to the Quarkus build mode, indicating that the dump was taken for the production build.

选择 ${project.basedir}/.quarkus 目录作为默认位置的原因是让它很容易跟踪构建之间的构建时间配置变更,并将其用作指示构建输出缓存工具(例如 Apache Maven Build CacheDevelocity Build Cache)是否必须重新构建应用程序二进制文件的指标。

The reason ${project.basedir}/.quarkus directory was chosen as the default location was to make it easy to track build time configuration changes between builds and use that as an indicator to build output caching tools (such as Apache Maven Build Cache and Develocity Build Cache) whether the application binary has to be re-built.

Filtering configuration options

可以通过使用逗号分隔的要过滤掉的配置选项名称来配置 quarkus.config-tracking.exclude 来指示配置跟踪器从报告中排除某些选项。

Configuration tracker could be instructed to exclude some of the options from the report by configuring quarkus.config-tracking.exclude with a comma-separated list of configuration option names that should be filtered out.

Path values

默认情况下,具有以用户主目录开头的 absolute 路径值的配置选项将使用 Unix 主目录别名 '~' 替换用户主目录部分,并使用 / 作为路径元素分隔符进行转换。

Configuration options with absolute path values that begin with a user home directory are, by default, transformed with Unix home directory alias '~' replacing the user home directory part and using / as a path element separator.

可以通过将 quarkus.config-tracking.use-user-home-alias-in-paths 设置为 false 来禁用此转换。

This transformation can be disabled by setting quarkus.config-tracking.use-user-home-alias-in-paths to false.

Hashing recorded configuration values

在将配置值写入文件之前,可以使用 SHA-512 算法对它们进行哈希处理。应哈希处理其值配置选项的名称可以作为逗号分隔列表配置在 quarkus.config-tracking.hash-options 中。

Configuration values can be hashed using SHA-512 algorithm before they are written to a file. Configuration option names whose values should be hashed can be configured in quarkus.config-tracking.hash-options as a comma separated list.

Tracking build time configuration changes between builds

虽然 quarkus.config-tracking.enabled 启用了有效的构建时配置报告生成,但还有办法在启动项目的下一次构建之前检查存储在该报告中的值是否发生更改。

While quarkus.config-tracking.enabled enables effective build time configuration report generation, there is also a way to check whether the values stored in that report have changed before the next build of the project is launched.

Maven 项目可以将以下目标添加到其 quarkus-maven-plugin 配置中:

Maven projects could add the following goal to their quarkus-maven-plugin configuration:

      <plugin>
        <groupId>${quarkus.platform.group-id}</groupId>
        <artifactId>quarkus-maven-plugin</artifactId>
        <version>${quarkus.platform.version}</version>
        <extensions>true</extensions>
        <executions>
          <execution>
            <id>track-prod-config-changes</id>
            <phase>process-resources</phase>
            <goals>
              <goal>track-config-changes</goal>
            </goals>
          </execution>
          <!-- other executions would follow below -->

track-config-changes 目标查找 ${project.basedir}/.quarkus/quarkus-prod-config-dump (文件名和目录是可配置的),如果文件已存在,则检查 config 转储中存储的值是否已更改。它将记录更改的选项,并将 ${project.basedir}/.quarkus/quarkus-prod-config-dump 中存在的每个选项的当前值保存在 ${project.basedir}/target/quarkus-prod-config.check 中(目标文件名和位置可以配置)。如果自上次构建以来构建时配置没有更改,则 ${project.basedir}/.quarkus/quarkus-prod-config-dump${project.basedir}/.quarkus/quarkus-prod-config-dump 将相同。

The track-config-changes goal looks for ${project.basedir}/.quarkus/quarkus-prod-config-dump (file name and directory are configurable) and, if the file already exists, checks whether the values stored in the config dump have changed. It will log the changed options and save the current values of each of the options present in ${project.basedir}/.quarkus/quarkus-prod-config-dump in ${project.basedir}/target/quarkus-prod-config.check (the target file name and location can be configured). If the build time configuration has not changed since the last build both ${project.basedir}/.quarkus/quarkus-prod-config-dump and ${project.basedir}/.quarkus/quarkus-prod-config-dump will be identical.

Dump Quarkus application dependencies

除了转储配置值之外,track-config-changes 目标还会转储所有 Quarkus 应用程序依赖项,包括 Quarkus 构建时依赖项。例如,该文件可用于检查自上次运行以来 Quarkus 构建类路径是否已更改,以及 Develocity 计算类路径校验和的能力。默认情况下,依赖项列表将存储在 target/quarkus-prod-dependencies.txt 文件下。可以使用插件参数配置不同的位置。

In addition to dumping configuration values, track-config-changes goal also dumps all the Quarkus application dependencies, including Quarkus build time dependencies. This file could be used to check whether Quarkus build classpath has changed since the previous run, for instance together with Develocity’s ability to checksum a classpath. By default, the list of dependencies will be stored under target/quarkus-prod-dependencies.txt file. A different location could be configured using plugin parameters.

Dump current build configuration when the recorded configuration isn’t found

默认情况下,track-config-changes 会查找在之前的构建期间记录的配置,如果找不到,它不会执行任何操作。启用 dumpCurrentWhenRecordedUnavailable 参数将使其转储当前构建配置选项,同时考虑 quarkus.config-tracking.* 配置。

By default, track-config-changes looks for the configuration recorded during previous build and does nothing if it’s not found. Enabling dumpCurrentWhenRecordedUnavailable parameter will make it dump the current build configuration options taking into account quarkus.config-tracking.* configuration.

quarkus:build 目标期间记录的构建配置选项不同,quarkus:track-config-changes 在启用 dumpCurrentWhenRecordedUnavailable 的情况下保存的配置选项将包括 org.eclipse.microprofile.config.Config 实例公开的所有构建配置选项。这意味着此报告可能包含不会被 Quarkus 应用程序构建过程使用的构建配置选项,但还可能缺少一些构建配置选项,因为 MicroProfile Config 规范允许配置源不向用户公开它们提供的全部属性名称。

Unlike the build configuration options recorded during the quarkus:build goal, configuration options saved by quarkus:track-config-changes with dumpCurrentWhenRecordedUnavailable enabled will include all the build configuration options exposed by a org.eclipse.microprofile.config.Config instance. Which means this report may include some build configuration options that will not be used by the Quarkus application build process but also may be missing some build configuration options since MicroProfile Config specification allows configuration sources not to expose all the property names they provide to users.

Config property values injected during static initialization phase

Quarkus 在 static initialization phase 期间收集注入在 CDI Bean 中的配置属性值。然后将收集到的值与其运行时初始化对应的值进行比较,如果检测到不匹配,则应用程序启动失败。怎么会这样?例如,我们有一个 CDI Bean org.acme.MyBeanMyBean 注入了一个名称为 foo@ConfigProperty,并在原生构建期间进行初始化。在原生构建期间,配置属性不存在,因此使用默认值 bar。但是,稍后,当应用程序启动时,该属性使用系统属性定义:-Dfoo=baz。这将导致状态不一致和行为意外。因此,Quarkus 在这种情况下默认会失败。

Quarkus collects the config property values injected in CDI beans during static initialization phase. The collected values are then compared with their runtime initialization counterparts and if a mismatch is detected the application startup fails. How can it happen? For example, let’s have a CDI bean org.acme.MyBean. MyBean injects a @ConfigProperty of name foo and is initialized during the native build. The config property does not exist during the native build and so the default value bar is used. But later, when the application is started the property is defined with a system property: -Dfoo=baz. This would lead to inconsistent state and unexpected behavior. Therefore, Quarkus would fail in this situation by default.

package org.acme;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.context.Initialized;
import org.eclipse.microprofile.config.inject.ConfigProperty;

@ApplicationScoped
public class MyBean {

   @ConfigProperty(name = "foo", defaultValue = "bar") 1
   String foo;

    void onInit(@Observes @Initialized(ApplicationScoped.class) Object event) { 2
       // this observer method is notified during STATIC_INIT...
    }
}
1 The config property is injected when the bean is created and the value is fixed.
2 In this particular case, the observer @Initialized(ApplicationScoped.class) caused the initialization of the bean. However, there are other possibilities. For example, some extensions initialize components during static initialization phase.

你可以在注入的字段/参数上使用 @io.quarkus.runtime.annotations.StaticInitSafe 注释,标记注入的配置对象可在静态初始化阶段安全初始化。

You can annotate an injected field/parameter with @io.quarkus.runtime.annotations.StaticInitSafe to mark the injected configuration object as safe to be initialized during the static initialization phase.

package org.acme;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import jakarta.enterprise.context.Initialized;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import io.quarkus.runtime.annotations.StaticInitSafe;

@ApplicationScoped
public class MyBeanNoFailure {

   @StaticInitSafe 1
   @ConfigProperty(name = "foo", defaultValue = "bar")
   String foo;

    void onInit(@Observes @Initialized(ApplicationScoped.class) Object event) {
       // this observer method is notified during STATIC_INIT...
    }
}
1 Instructs Quarkus not to fail if a mismatch is detected.

Configuration Reference

Unresolved directive in config-reference.adoc - include::{generated-dir}/config/quarkus-core_quarkus.config.adoc[]