Configuring Your Application
本指南的内容已修订并拆分为其他主题。请查看 Additional Information 部分。
The content of this guide and been revised and split into additional topics. Please check the additional-information section.
你代码中的硬编码值是一个 no-go(即使我们都曾经在某个时间点这样做过 ;-))。在本指南中,我们将学习如何配置 Quarkus 应用程序。
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.
Solution
我们建议您遵循接下来的部分中的说明,按部就班地创建应用程序。然而,您可以直接跳到完成的示例。
We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.
克隆 Git 存储库: git clone {quickstarts-clone-url}
,或下载 {quickstarts-archive-url}[存档]。
Clone the Git repository: git clone {quickstarts-clone-url}
, or download an {quickstarts-archive-url}[archive].
可以在 config-quickstart
directory 中找到解决方案。
The solution is located in the config-quickstart
directory.
Create the Maven project
首先,我们需要一个新项目。使用以下命令创建一个新项目:
First, we need a new project. Create a new project with the following command:
Unresolved directive in config.adoc - include::{includes}/devtools/create-app.adoc[]
它生成:
It generates:
-
the Maven structure
-
a landing page accessible on
http://localhost:8080
-
example
Dockerfile
files for bothnative
andjvm
modes -
the application configuration file
Create the configuration
Quarkus 应用程序使用 SmallRye Config API 提供与配置相关的全部机制。
A Quarkus application uses the SmallRye Config API to provide all mechanisms related with configuration.
默认情况下,Quarkus 会从 several sources 读取配置属性。为指引起见,我们将使用位于 src/main/resources/application.properties
的应用程序配置文件。
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:
# Your configuration properties
greeting.message=hello
greeting.name=quarkus
Create a REST resource
使用以下内容创建 org.acme.config.GreetingResource
REST 资源:
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 使用 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. |
编辑 org.acme.config.GreetingResource
,引入以下配置属性:
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 . |
现在,修改 hello
方法,使用已注入的属性:
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 |
Store secrets in an environment properties file
出于安全考虑,不得在版本控制中保留机密(例如密码、个人访问令牌或 API 密钥)。一种方法是将它们存储在本地环境属性(.env
)文件中:
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:
-
Store the secret in the
.env
file in the project root directory.[source, properties] .The .env file
foo.api-key=ThisIsSecret
-
Add the
.env
file to.gitignore
.
mvn quarkus:dev
会自动提取 .env
文件中的属性,类似于 application.properties
文件中的属性。
mvn quarkus:dev
automatically picks up the properties in the .env
file,
similar to those in the application.properties
file.
Update the test
我们还需要更新功能测试以反映对端点所做的更改。使用以下内容创建 src/test/java/org/acme/config/GreetingResourceTest.java
文件:
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
}
}
Package and run the application
使用以下内容运行应用程序:
Run the application with:
Unresolved directive in config.adoc - include::{includes}/devtools/dev.adoc[]
用浏览器打开 [role="bare"][role="bare"]http://localhost:8080/greeting.
Open your browser to [role="bare"]http://localhost:8080/greeting.
更改配置文件会立即反映出来。您可以添加 greeting.suffix
、删除其他属性、更改值等。
Changing the configuration file is immediately reflected.
You can add the greeting.suffix
, remove the other properties, change the values, etc.
和往常一样,可以使用以下命令打包应用程序:
As usual, the application can be packaged using:
Unresolved directive in config.adoc - include::{includes}/devtools/build.adoc[]
并使用 java -jar target/quarkus-app/quarkus-run.jar
执行。
and executed using java -jar target/quarkus-app/quarkus-run.jar
.
你还可以按如下方式生成本机可执行文件:
You can also generate the native executable with:
Unresolved directive in config.adoc - include::{includes}/devtools/build-native.adoc[]
Programmatically access the configuration
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);
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 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.
Additional Information
Quarkus 依赖于 SmallRye Config 并继承其特性:
Quarkus relies on SmallRye Config and inherits its features:
-
Additional `ConfigSource`s
-
Additional `Converter`s
-
Indexed properties
-
Parent profile
-
Interceptors for configuration value resolution
-
Relocate configuration properties
-
Fallback configuration properties
-
Logging
-
Hide secrets
欲了解更多信息,请查看 SmallRye Config documentation。
For more information, please check the SmallRye Config documentation.