Both the Quarkus application and Quarkus itself (core and extension) are configured through the same mechanism, which leverages the SmallRye Config API and the MicroProfile Config specification implementation. In addition, Quarkus itself offers some additional features.

1. The configuration source

By default, Quarkus reads configuration properties from multiple sources (with decreasing priority) :

  1. System property
  2. The environment variable
  3. Env is placed in the current working directory
  4. The application.properties file is placed in the $PWD/config/ directory
  5. Application configuration files, that is, SRC/main/resources/application. The properties

1.1. System attributes

  • Run the jar: Java – Dquarkus. The datasource. Password = youshallnotpass – jar target/quarkus – app/quarkus – run. The jar
  • Native executable files: / target/myapp – runner – Dquarkus. The datasource. Password = youshallnotpass

1.2. Environment variables

  • Run jar: export QUARKUS_DATASOURCE_PASSWORD= youshallNotPass; java -jar target/quarkus-app/quarkus-run.jar

  • Native executable file: export QUARKUS_DATASOURCE_PASSWORD= youshallNotPass; ./target/myapp-runner

1.3. The file name. Env is placed in the current working directory

Example. Env file

'QUARKUS_DATASOURCE_PASSWORD= YoushallNotPass' QUARKUS_DATASOURCE_PASSWORD uses the same rules as environment variables to convert names. `Copy the code

For developer mode, this file can be placed in the root of the project, but it is not recommended to check it into version control.

The. Env file of an environment variable that is not defined in a configuration file will override all of its associated application.properties profiles, for example, %test.application.value will override APPLICATION_VALUE.

1.4. The application. The properties files are placed in $PWD/config /

Place the application.properties file in a directory called config, which is in the directory where the application runs, and all the runtime properties defined in this file will override the default configuration. In addition, any runtime attributes added to the file that were not part of the original application.properties file _ will also be taken into account. It works the same way for the running program JAR and the native executable.

The config/application. The function of the properties can also be used in the development mode. To use it, the config/application. The properties in the need to be placed in the output directory of the build tools (target for Maven and build/classes/Java/mainGradle). Keep in mind, however, that any cleanup from the build tool (such as MVN clean or) gradle Clean will also remove the config directory.

1.5. Application configuration files

This is located in the main application configuration files in the SRC/main/resources/application properties.

Sample application.properties file

`greeting.message=hello` 
`quarkus.http.port=9090` 
Copy the code
  • This is a user-defined configuration property.
  • This is a user-defined configuration property.
  • Quarkus supports the use of attribute expressions application.properties in files.

2. Embed the configuration file in the dependency

You can embed the profile by adding a profile to the meta-INF /microprofile-config.properties profile (this is a standard feature of Microprofile Config).

When this dependency is added to the application, its configuration properties are merged.

You can override attributes that precede it from its property application.properties.

3. Inject configuration properties

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

`@ConfigProperty(name = "greeting.message")` `String message; `Copy the code

You can use @inject @configProperty or @configProperty. For members annotated with @inject, annotations are not required by @configProperty. This behavior differs from MicroProfile Config.

If the application tries to inject configuration properties that are not set, an error is thrown, allowing you to quickly know when the configuration is complete.

More @configProperty examples

`@ConfigProperty(name = "greeting.message")` `String message; ` `@ConfigProperty(name = "greeting.suffix", defaultValue="!" )` `String suffix; ` `@ConfigProperty(name = "greeting.name")` `Optional<String> name; `Copy the code

If you do not provide the value of this attribute, then the application will start failure javax.mail. Enterprise. Inject. Spi. DeploymentException: No config value of type [class java.lang.string] exists for: greeting.message.

If you configure a value that is not provided, the default greeting.suffix is injected.

This property is Optional. If no value is provided, a null value greeting.name is injected.

4. Access the configuration programmatically

Configuration can be accessed programmatically. It can be convenient to implement dynamic lookup or retrieval of configured values from classes that are neither CDI beans nor JAX-RS resources.

Can use the following ways to programmatically access configuration org. The eclipse microprofile. Config. ConfigProvider. GetConfig () :

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

5. Using the @ ConfigProperties

As shown in the above a sample way into multiple related configuration values of alternative, the user can also use the @ IO. Quarkus. Arc. Config. ConfigProperties comments to these attributes together.

For the Greeting property above, GreetingConfiguration creates a class like this:

`package org.acme.config; ` `import io.quarkus.arc.config.ConfigProperties; ` `import java.util.Optional; ` `@ConfigProperties(prefix = "greeting")` `public class GreetingConfiguration {` `private String message; ` `private String suffix = "!" ; ` `private Optional<String> name; ` `public String getMessage() {` `return message; ` `}` `public void setMessage(String message) {` `this.message = message; ` `}` `public String getSuffix() {` `return suffix; ` `}` `public void setSuffix(String suffix) {` `this.suffix = suffix; ` `}` `public Optional<String> getName() {` `return name; ` `}` `public void setName(Optional<String> name) {` `this.name = name; ` ` `} ` `}Copy the code

GreetingResource can then Inject this class into the CDI annotation @Inject, as shown below:

`@Inject` `GreetingConfiguration greetingConfiguration; `Copy the code

Another alternative style provided by Quarkus is that GreetingConfiguration creates interfaces like this:

`package org.acme.config; ` `import io.quarkus.arc.config.ConfigProperties; ` `import org.eclipse.microprofile.config.inject.ConfigProperty; ` `import java.util.Optional; ` `@ConfigProperties(prefix = "greeting")` `public interface GreetingConfiguration {` `@ConfigProperty(name = "message")` `String message(); ` `@ConfigProperty(defaultValue = "!" )` `String getSuffix(); ` `Optional<String> getName(); ` ` `}Copy the code

When used in @ ConfigProperties class or interface, if you do not provide the value of one of the fields, then the application startup will fail, and the javax.mail. Enterprise. Inject. Spi. DeploymentException display indicating a lack of information. This does not apply to Optional fields and fields with default values.

5.1. Additional instructions regarding @ConfigProperties

When using regular classes with class annotations, @ConfigProperties does not necessarily have to declare getters and setters. It is also valid to have simple common non-final fields.

In addition, the configuration class supports nested object configuration. Assuming an additional greeting configuration layer is required, the name Content will contain some fields. This can be done like this:

`@ConfigProperties(prefix = "greeting")` `public class GreetingConfiguration {` `public String message; ` `public String suffix = "!" ; ` `public Optional<String> name; ` `public ContentConfig content; ` `public static class ContentConfig {` `public Integer prizeAmount; ` `public List<String> recipients; ` ` `} ` `}Copy the code

The field name (not the class name) determines the name of the property bound to the object.

Setting the properties would be done in the normal way, for example, application.properties might have:

`greeting.message = hello`
`greeting.name = quarkus`
`greeting.content.prize-amount=10`
`greeting.content.recipients=Jane,John`
Copy the code

In addition, @ConfigProperties can annotate classes that use annotations using Bean Validation annotations, similar to the following example:

`@ConfigProperties(prefix = "greeting")` `public class GreetingConfiguration {` `@Size(min = 20)` `public String message; ` `public String suffix = "!" ; ` ` `}Copy the code

For validation to work, Quarkus-Hibernate-Validator needs to provide an extension

If validation fails with the given configuration, the application will not start and the corresponding validation error will be indicated in the log.

If an interface has the @configProperties annotation, it is allowed to extend other interfaces and bind properties using methods in the entire interface hierarchy.

5.2. Use the same ConfigProperty with a different prefix

Quarkus also supports using the @ConfigProperties annotation to use the same object with a different prefix io.quarkus.arc.config.@ConfigPrefix for each injection point. For example, both the prefix and the GreetingConfiguration prefix require the above code. In this case, the code looks like this: greetingother

GreetingConfiguration.java

`@ConfigProperties(prefix = "greeting")` `public class GreetingConfiguration {` `@Size(min = 20)` `public String message; ` `public String suffix = "!" ; ` ` `}Copy the code

SomeBean.java

`@ApplicationScoped` `public class SomeBean {` `@Inject` `GreetingConfiguration greetingConfiguration; ` `@ConfigPrefix("other")` `GreetingConfiguration otherConfiguration; ` ` `}Copy the code

5.3. Using object lists

In some cases, it may be necessary to support complex configuration structures that leverage object lists, as shown in the following example:

ComplexConfiguration.java

`@ConfigProperties(prefix = "complex")` `public class ComplexConfiguration {` `public String name; ` `public String user; ` `public String password; ` `public List<Nested> inputs; ` `public List<Nested> outputs; ` `public static class Nested {` `public String user; ` `public String password; ` ` `} ` `}Copy the code

This type of use case is supported only if the YAML configuration is used with the Quarkus-config-YAMl extension. The corresponding sample YAML configuration could be:

application.yaml

`complex:` `name: defaultName` `user: defaultUser` `password: defaultPassword` `inputs:` `- user: user` `password: secret` `- user: otheruser` `password: secret2` `outputs:` `- user: someuser` `password: asecret` `- user: Someotheruser ' 'password: anothersecret` ```* The limitation of this configuration is that the type used as the generic type of the list must be class and not interface 6. Configuration file ======== Quarkus supports the concept of configuration files. These allow you to have multiple configurations in the same file and choose between them by profile name. The syntax is %{profile}.config.key=value. For example, if I have the following:Copy the code

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

Unless the dev profile is active, the Quarkus HTTP port will be 9090, in which case it will be 8181. To use configuration files in. Env files, you can follow a \_{PROFILE}\_CONFIG\_KEY=value pattern. The equivalent of the above example in the.env file is:Copy the code

QUARKUS_HTTP_PORT=9090 _DEV_QUARKUS_HTTP_PORT=8181

Quarkus has three profiles by default, although you can use them as you like. The default configuration file is: ** *dev-** Activate tests in development mode (i.e. Quarkus :dev) ** * activate tests when running tests ** *prod-** Default configuration file when not running in development or test mode There are two ways to set up custom profiles through the Quarkus.profile system property or the quarkus \_PROFILE environment variable. If both are set, system properties take precedence. Note that you don't have to define the names of these profiles anywhere, just create the Config property with the profile name, and then set the current profile to that name. For example, if I wanted to staging a configuration file using another HTTP port, I could add the following to application.properties:Copy the code

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

I then set the QUARKUS\_PROFILE environment variable staging to activate my profile. Programmatically inspection activity configuration files of the correct method is to use the method of getActiveProfile IO. Quarkus.. The runtime configuration. ProfileManager. @configProperty ("quarkus.profile") will not ** work properly. 6.1. Default Run time Profile ============= The default Quarkus application run time profile is set to the profile used to build the application. Such as:Copy the code

Profile =prod-aws./target/my-app-1.0-runner./ MVNW package-pnative-dquarkus. profile=prod-aws./target/my-app-1.0-runner

This command will run with the prod- AWS profile. You can override it using the Quarkus.profilesystem property. 7. Use property expressions ========= Quarkus supports using property expressions in application.properties files. After reading the properties, these expressions are parsed. Therefore, if your configuration property is a build-time configuration property, the property expression will be resolved at build time. If your configuration property is overridden at run time, the property expression is resolved at run time. You can use property expressions for both Quarkus configurations or for your own configuration properties. Property expressions are defined as ${my-property-expression}. For example, have the following attributes:Copy the code

remote.host=quarkus.io

Another attribute is defined as:Copy the code

callable.url=https://${remote.host}/

Causes the callable. Url property to be set to:Copy the code

callable.url=quarkus.io/

Another example is to define different database servers based on the profiles used:Copy the code

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

This can be simplified in the following ways:Copy the code

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

In this case, it does add a row, but the value application.server can be reused in other properties, reducing the possibility of typing errors and providing greater flexibility in property definitions. 8. Combining attribute expressions and environment variables ============== Quarkus also supports combining attribute expressions and environment variables. Suppose you define the following property application.properties in:Copy the code

remote.host=quarkus.io

You can combine environment variables and attribute expressions by defining attributes as follows:Copy the code

application.host={HOST:{remote.host}}

If not set, this extends the HOST environment variable and uses the value of the property remote. HOST as the default value HOST. For the purposes of this section, we use the properties defined previously by remote.host. It must be noted that this value can be fixed, for example:Copy the code

application.host=${HOST:localhost}

Localhost If HOST is not set, it will be used as the default. 9. Configure Quarkus =========== Quarkus itself is configured through the same mechanism as your application. Quarkusquarkus. Reserve namespaces for your own configuration and all of its extended configurations. For example, to configure the HTTP server port, set application.properties in quarkus.http.port. All Quarkus configuration properties are recorded and searchable. Quarkus does most of the configuration and boot at build time, and some configuration properties are read and used during build. These attributes _ are _ fixed _ at build time and cannot be changed at run time. You always need to repackage the application to reflect changes to such properties. * Properties that are fixed at build time are marked with a lock icon () in the list of all configuration options. However, some extenders do define attributes that can be overridden at run time. A typical example is the database URL, username, and password, which are only known in your target environment. This is a tradeoff, because the more run-time attributes available, the less build time Quarkus can do. Therefore, the run-time property list is lean. You can override these runtime properties (with reduced priority) using the following mechanism: 1. System properties 2. Environment variables 3. Named environment file. Env in the current working directory 4. Placed in the configuration file $PWD/config/application. The properties for more details, please see the configuration source. 10. Configuration for application generation ============ can also generate an example of application.properties with all known configuration properties to make it easy to view the available Quarkus configuration options. To do this, run:Copy the code

./mvnw quarkus:generate-config

This will create a SRC/main/resources/application properties. The example file, which contains through your current installation extension open all configuration options. These options are commented out and have their default values when applicable. For example, this HTTP port configuration entry would appear as:Copy the code

# # The HTTP port # #quarkus.http.port=8080

In addition to generating sample configuration files, you can add them to the actual configuration file by setting the \ -dfile parameter:Copy the code

./mvnw quarkus:generate-config -Dfile=application.properties

If the configuration option already exists (annotated), it will not be added, so it is safe to run the configuration option after adding additional extensions to see what other options have been added. 11. Clear properties ======= You can explicitly clear runtime properties by assigning an empty string to properties that are optional and have values set at build time or have default values. Note that this _ only affects runtime attributes, and _ can only be used with attributes that do not require their value. You can clear this property by setting the appropriate application.properties property, setting the appropriate system properties, or setting the appropriate environment variables. 12. Custom configuration ======== 12.1. Custom configuration source ========== You can also use standard MicroProfile Config to introduce custom configuration sources. To this end, You must provide an implementation of org. Eclipse. Microprofile. Config. The spi. ConfigSource or class org. Eclipse microprofile. Config. Spi. ConfigSourceProvider. Create a service file for the class, which will be detected and installed when the application starts. 12.2. Custom Configuration Converter ============ You can also use custom types for configuration values. This can be achieved by org. Eclipse. Microprofile. Config. Spi. The Converter < T > In the meta-inf/services/org. The eclipse microprofile. Config. Spi. The Converter file implementation and add the fully qualified class name. Let's assume you have a custom type that looks like this:Copy the code

package org.acme.config; public class MicroProfileCustomValue { private final int number; public MicroProfileCustomValue(int number) { this.number = number; } public int getNumber() { return number; }}

The corresponding converter is shown below. Note that your custom converter class must be public and must have a public no-argument constructor. It must not be abstract.Copy the code

package org.acme.config; import org.eclipse.microprofile.config.spi.Converter; public class MicroProfileCustomValueConverter implements Converter

{ @Override public MicroProfileCustomValue convert(String value) { return new MicroProfileCustomValue(Integer.parseInt(value)); }}

Then, you need in the service document contains Converter standard class name meta-inf/services/org. The eclipse microprofile. Config. Spi. The Converter. If you have more converters, simply add their class names to their files as well. A fully qualified class name per line, for example:Copy the code

org.acme.config.MicroProfileCustomValueConverter org.acme.config.SomeOtherConverter org.acme.config.YetAnotherConverter

Note that SomeOtherConverter and YetAnotherConverter were added for demonstration purposes only. If you include classes in this file that are not available at run time, the converter load will fail. When this is done, you can use custom types as configuration values:Copy the code

@ConfigProperty(name = "configuration.value.name") MicroProfileCustomValue value;

12.2.1. Converter priority ============= In some cases, you may want to use a custom converter to convert a type that has already been converted by another converter. . In this case, you can use the javax.mail annotation. The Priority comments to change the Priority of converter, and make the custom converter the Priority of the other switches in the above list. By default, @priority has a Priority of 100 if it can't find No on the converter. All Quarkus core converters have a Priority of 200, so a higher value needs to be set depending on which converter is being replaced. To illustrate this idea, let us do a custom converter, the converter will give priority to MicroProfileCustomValueConverter in an example on the implementation of the converter.Copy the code

package org.acme.config; import javax.annotation.Priority; import org.eclipse.microprofile.config.spi.Converter; @Priority(150) public class MyCustomConverter implements Converter

{ @Override public MicroProfileCustomValue convert(String value) { final int secretNumber; if (value.startsFrom(“OBF:”)) { secretNumber = Integer.parseInt(SecretDecoder.decode(value)); } else { secretNumber = Integer.parseInt(value); } return new MicroProfileCustomValue(secretNumber); }}

Because it will convert the value of the same type (i.e. MicroProfileCustomValue), and priority for 150, so will use the default priority MicroProfileCustomValueConverter for 100 a instead of it. The new Converter needs to be listed in the service file, namely the meta-inf/services/org. The eclipse microprofile. Config. Spi. The Converter. 13 \. YAML configuration = = = = = = = = = = = 13.1. Add YAML configuration support = = = = = = = = = = = = = = = you might want to attribute using YAML configuration. Because SmallRye Config comes with support for YAML configurations, Quarkus also supports this. First, you need to add the Config YAML extension to your POM.xml:Copy the code

<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-config-yaml</artifactId> </dependency>

Alternatively, you can run the following command in the directory that contains the Quarkus project:Copy the code

./mvnw quarkus:add-extension -Dextensions=”config-yaml”

Quarkus can now read YAML configuration files. The configuration directory and priority are the same as before. Quarkus will select Application.yaml an application.properties. YAML files are just another way to configure your application. You should identify and retain a configuration type to avoid errors. 13.1.1. Configuration Example ===========Copy the code

# YAML supports comments quarkus: datasource: db-kind: postgresql jdbc: url: jdbc:postgresql://localhost:5432/some-database username: quarkus password: quarkus # REST Client configuration property org: acme: restclient: CountriesService/mp-rest/url: https://restcountries.eu/rest # For configuration property names that use quotes, do not split the string inside the quotes. quarkus: log: category: "io.quarkus.category": level: INFO

Quarkus also supports the use of application.yml as YAML file names. This file is the same as the rule application.yaml. 13.2. Configuration depends on the configuration file =============== As with properties, the same is true for configuration file related configurations provided through YAML. %profile simply adds quotes wrapped in quotes before defining key/value pairs:Copy the code

"%dev": quarkus: datasource: db-kind: postgresql jdbc: url: jdbc:postgresql://localhost:5432/some-database username: quarkus password: quarkus

13.3. Configure key conflicts =========== The MicroProfile Config specification defines the configuration key as an arbitrary,. Delimit strings. However, structured formats like YAML naively support only a subset of possible configuration namespaces. For example, consider two configuration properties quarkus. HTTP. Cors and quarkus. HTTP. Cors. The methods. One attribute is a prefix to another, so it may not be obvious how to specify both keys in your YAML configuration. This can be solved by using the null key (typically represented by ~), which is another prefix, on any YAML attribute. Here is an example: _ Example YAML configuration _ to resolve key name conflicts related to prefixesCopy the code

quarkus: http: cors: ~: true methods: GET,PUT,POST

In general, nullYAML keys are not included in the compilation of configuration property names, allowing them to be used to disambiguously configure keys at any level. 14. For more information on how to configure ============== Quarkus relies on SmallRye Config and inherits its functionality. SmallRye Config provides: * Additional configuration sources * Additional converters * indexed attributes * parent information * Interceptors for configuration value resolution * repositioned configuration attributes * backup configuration attributes * Hidden secrets in recordsCopy the code