1. Overview
1.概述
Properties are one of the most useful mechanisms provided by Spring Boot. They may be provided from various places such as dedicated properties files, environment variables, etc. Because of that, it’s sometimes useful to find and log specific properties, for example while debugging.
属性是Spring Boot提供的最有用的机制之一。它们可以从不同的地方提供,如专用的属性文件、环境变量等。正因为如此,有时查找和记录特定的属性是很有用的,例如在调试时。
In this short tutorial, we’ll see a few different ways to find and log properties in a Spring Boot application.
在这个简短的教程中,我们将看到在Spring Boot应用程序中查找和记录属性的几种不同方法。
First, we’ll create a simple test app that we’ll work on. Then, we’ll try three different ways to log specific properties.
首先,我们将创建一个简单的测试应用程序,我们将在上工作。然后,我们将尝试三种不同的方式来记录特定属性。
2. Creating a Test Application
2.创建一个测试应用程序
Let’s create a simple app with three custom properties.
让我们创建一个有三个自定义属性的简单应用。
We can use Spring Initializr to create a Spring Boot app template. We’ll use Java as the language. We’re free to choose other options such as Java version, project metadata, etc.
我们可以使用Spring Initializr来创建一个Spring Boot应用模板。我们将使用Java作为语言。我们可以自由选择其他选项,如Java版本、项目元数据等。
The next step is to add custom properties to our app. We’ll add those properties to a new application.properties file in src/main/resources:
下一步是为我们的应用程序添加自定义属性。我们将把这些属性添加到application.properties文件中,在src/main/resources。
app.name=MyApp
app.description=${app.name} is a Spring Boot application
bael.property=stagingValue
3. Logging Properties With Context Refreshed Event
3.用上下文刷新事件记录属性
The first way of logging properties in a Spring Boot application is to use Spring Events, especially the org.springframework.context.event.ContextRefreshedEvent class and the corresponding EventListener. We’ll show how to log all available properties and a more detailed version that prints properties only from a specific file.
在Spring Boot应用程序中记录属性的第一种方式是使用Spring Events,特别是org.springframework.context.event.ContextRefreshedEvent类和相应的EventListener。我们将展示如何记录所有可用属性以及仅从特定文件打印属性的更详细版本。
3.1. Logging All Properties
3.1.记录所有属性
Let’s start with creating a bean and the event listener method:
让我们从创建一个Bean和事件监听器方法开始。
@Component
public class AppContextRefreshedEventPropertiesPrinter {
@EventListener
public void handleContextRefreshed(ContextRefreshedEvent event) {
// event handling logic
}
}
We annotate the event listener method with the org.springframework.context.event.EventListener annotation. Spring invokes the annotated method when ContextRefreshedEvent occurs.
我们用org.springframework.context.event.EventListener注解来注释事件监听器方法。当ContextRefreshedEvent发生时,Spring会调用注解的方法。
The next step is to get an instance of org.springframework.core.env.ConfigurableEnvironment interface from the triggered event. The ConfigurableEnvironment interface provides a useful method, getPropertySources(), that we’ll use to get a list of all property sources, such as environment, JVM or property file variables:
下一步是从触发的事件中获取org.springframework.core.env.ConfigurableEnvironment接口的一个实例。ConfigurableEnvironment接口提供了一个有用的方法,getPropertySources(),我们将用它来获取所有属性源的列表,例如环境、JVM或属性文件变量。
ConfigurableEnvironment env = (ConfigurableEnvironment) event.getApplicationContext().getEnvironment();
Now let’s see how we can use it to print all properties, not only from the application.properties file, but also from environment, JVM variables and many more:
现在让我们看看如何使用它来打印所有的属性,不仅是来自application.properties文件的属性,而且还有来自环境、JVM变量和更多的属性。
env.getPropertySources()
.stream()
.filter(ps -> ps instanceof MapPropertySource)
.map(ps -> ((MapPropertySource) ps).getSource().keySet())
.flatMap(Collection::stream)
.distinct()
.sorted()
.forEach(key -> LOGGER.info("{}={}", key, env.getProperty(key)));
Firstly, we create a Stream from available property sources. Then, we use its filter() method to iterate over property sources that are instances of the org.springframework.core.env.MapPropertySource class.
首先,我们创建一个Stream从可用属性源。然后,我们使用其filter()方法来遍历属性源,这些属性源是org.springframework.core.env.MapPropertySource类的实例。
As the name suggests, properties in that property source are stored in a map structure. We use this in the next step, in which we’re using the stream’s map() method to get the set of property keys.
正如其名,该属性源中的属性被存储在一个map结构中。我们在下一步中使用这个,我们使用流的map()方法来获取属性键的集合。
Next, we’re using Stream‘s flatMap() method, because we want to iterate over a single property key, not a set of keys. We also want to have unique, not duplicated, properties printed in alphabetical order.
接下来,我们使用Stream的flatMap()方法,因为我们想迭代单个属性键而不是一组键。我们还希望有唯一的,而不是重复的,按字母顺序打印的属性。
The last step is to log the property key and its value.
最后一步是记录属性键及其值。
When we start the app, we should see a big list of properties fetched from various sources:
当我们启动应用程序时,我们应该看到一个从各种来源获取的财产的大列表。
COMMAND_MODE=unix2003
CONSOLE_LOG_CHARSET=UTF-8
...
bael.property=defaultValue
app.name=MyApp
app.description=MyApp is a Spring Boot application
...
java.class.version=52.0
ava.runtime.name=OpenJDK Runtime Environment
3.2. Logging Properties Only From the application.properties File
3.2.只从application.properties文件中记录属性
If we want to log properties found in just the application.properties file, we can reuse almost all the code from earlier. We need to change only the lambda function passed to the filter() method:
如果我们想记录仅在application.properties文件中发现的属性,我们可以重复使用先前的几乎所有代码。我们只需要改变传递给filter()方法的lambda函数。
env.getPropertySources()
.stream()
.filter(ps -> ps instanceof MapPropertySource && ps.getName().contains("application.properties"))
...
Now, when we start the app, we should see the following logs:
现在,当我们启动应用程序时,我们应该看到以下日志。
bael.property=defaultValue
app.name=MyApp
app.description=MyApp is a Spring Boot application
4. Logging Properties With Environment Interface
4.用环境接口记录属性
Another way to log properties is to use the org.springframework.core.env.Environment interface:
另一种记录属性的方式是使用 org.springframework.core.env.Environment接口。
@Component
public class EnvironmentPropertiesPrinter {
@Autowired
private Environment env;
@PostConstruct
public void logApplicationProperties() {
LOGGER.info("{}={}", "bael.property", env.getProperty("bael.property"));
LOGGER.info("{}={}", "app.name", env.getProperty("app.name"));
LOGGER.info("{}={}", "app.description", env.getProperty("app.description"));
}
}
The only limitation compared to the context refreshed event approach is that we need to know the property name to get its value. The environment interface doesn’t provide a method to list all properties. On the other hand, it’s definitely a shorter and easier technique.
与上下文刷新事件的方法相比,唯一的限制是我们需要知道属性名称来获取其值。环境接口没有提供一个方法来列出所有的属性。另一方面,这绝对是一个更短、更容易的技术。
When we start the app, we should see the same output as earlier:
当我们启动应用程序时,我们应该看到与先前相同的输出。
bael.property=defaultValue
app.name=MyApp
app.description=MyApp is a Spring Boot application
5. Logging Properties With Spring Actuator
5.使用Spring推杆的记录属性
Spring Actuator is a very useful library that brings production-ready features to our application. The /env REST endpoint returns the current environment properties.
Spring Actuator是一个非常有用的库,它为我们的应用程序带来了可用于生产的功能。/env REST端点返回当前环境属性。
First, let’s add Spring Actuator library to our project:
首先,让我们把Spring Actuator库添加到我们的项目中。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.7.3</version>
</dependency>
Next, we need to enable the /env endpoint, because it’s disabled by default. Let’s open application.properties and add the following entries:
接下来,我们需要启用/env端点,因为它默认是禁用的。让我们打开application.properties并添加以下条目。
management.endpoints.web.exposure.include=env
Now, all we’ve to do is start the app and go to the /env endpoint. In our case the address is http://localhost:8080/actuator/env. We should see a large JSON containing all environment variables including our properties:
现在,我们所要做的就是启动应用程序,并进入/env端点。在我们的例子中,这个地址是http://localhost:8080/actuator/env。我们应该看到一个包含所有环境变量的大型JSON,包括我们的属性。
{
"activeProfiles": [],
"propertySources": [
...
{
"name": "Config resource 'class path resource [application.properties]' via location 'optional:classpath:/' (document #0)",
"properties": {
"app.name": {
"value": "MyApp",
"origin": "class path resource [application.properties] - 10:10"
},
"app.description": {
"value": "MyApp is a Spring Boot application",
"origin": "class path resource [application.properties] - 11:17"
},
"bael.property": {
"value": "defaultValue",
"origin": "class path resource [application.properties] - 13:15"
}
}
}
...
]
}
6. Conclusion
6.结语
In this article, we learned how to log properties in a Spring Boot application.
在这篇文章中,我们学习了如何在Spring Boot应用程序中记录属性。
First, we created a test application with three custom properties. Then, we saw three different ways to retrieve and log desired properties.
首先,我们创建了一个具有三个自定义属性的测试应用程序。然后,我们看到了三种不同的方法来检索和记录所需的属性。
As always, the complete source code of the article is available over on GitHub.
一如既往,该文章的完整源代码可在GitHub上获得。