IntelliJ 使用Spring 配置属性元数据
1. 概述
当我们将运行时属性注入 Spring 应用程序时,我们可以为自定义属性组定义 bean 类 。
IntelliJ 为内置属性 bean 提供帮助和自动完成功能。但是,为自定义属性提供这些需要一点帮助。
在这个简短的教程中,我们将了解如何将这些属性公开给 IntelliJ 以简化开发过程。
2. 自定义属性
让我们看一下 IntelliJ 可以为我们提供的有关应用程序属性的屏幕帮助:
这里,属性url和timeout-in-milliseconds 是自定义属性。我们可以看到描述、类型和可选的默认值。
但是,如果属性未知,IntelliJ 会向我们显示警告:
这是因为,没有元数据,IntelliJ 无法帮助我们。
现在让我们看看我们必须做些什么来解决这个问题。
3. 依赖关系
首先,我们需要将spring-boot-configuration-processor 依赖添加到我们的pom.xml中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
每次构建项目时都会调用spring-boot-configuration-processor。它将在target/classes/META-INF/ 中创建元数据文件。
该依赖被标记为可选,这意味着当有人将我们的项目用作依赖时,它不会被继承。
接下来,我们将看到spring-boot-configuration-processor从何处获取用于创建元数据的信息。
4. 带有*@ConfigurationProperties*的配置元数据
我们在使用*@ConfigurationProperties*注解的类中定义我们的属性:
@Configuration
@ConfigurationProperties(prefix = "com.blogdemo")
public class CustomProperties {
/**
* The url to connect to.
*/
String url;
/**
* The time to wait for the connection.
*/
private int timeoutInMilliSeconds = 1000;
// Getters and Setters
}
在这里,类包含属性名称、它们的类型以及初始化列表中提供的任何默认值。此外,Javadoc 还提供了每个属性的描述。
在构建期间,*注解处理器会搜索所有使用@ConfigurationProperties*进行注解的类。**它为类的每个实例变量生成自定义属性元数据。
5. 配置元数据文件
5.1.元数据文件的格式
描述自定义属性的元数据文件 驱动 IntelliJ 中的上下文帮助,例如:
{
"groups": [
{
"name": "com.blogdemo",
"type": "com.blogdemo.configuration.processor.CustomProperties",
"sourceType": "com.blogdemo.configuration.processor.CustomProperties"
}
],
"properties": [
{
"name": "com.blogdemo.url",
"type": "java.lang.String",
"description": "The url to connect to.",
"sourceType": "com.blogdemo.configuration.processor.CustomProperties"
},
{
"name": "com.blogdemo.timeout-in-milli-seconds",
"type": "java.lang.Integer",
"description": "The time to wait for the connection.",
"sourceType": "com.blogdemo.configuration.processor.CustomProperties",
"defaultValue": 1000
}
],
"hints": []
}
由于注解处理器会根据我们的代码为我们生成此文件,因此无需直接查看或编辑此文件。
5.2. 没有ConfigurationProperties Bean的元数据
如果我们有*@ConfigurationProperties*未引入的现有属性,但仍需要它们的元数据文件,那么 IntelliJ 可以提供帮助。
让我们仔细看看之前的警告信息:
在这里,我们看到了一个定义配置键选项,我们可以使用它来创建一个json文件。创建的文件将如下所示:
{
"properties": [
{
"name": "com.blogdemo.timeoutInMilliSeconds",
"type": "java.lang.String",
"description": "Description for com.blogdemo.timeoutInMilliSeconds."
}
]
}
由于没有来自其他任何地方的关于该属性的信息,**我们必须手动编辑其中的元数据。**默认type始终为String。
让我们在文件中添加一些额外的信息:
{
"properties": [
{
"name": "com.blogdemo.timeout-in-milli-seconds",
"type": "java.lang.Integer",
"description": "The time to wait for the connection.",
"sourceType": "com.blogdemo.configuration.processor.CustomProperties",
"defaultValue": 1000
}
]
}
请注意,我们需要重建项目才能看到新属性出现在 auto-complete中。
此外,我们应该注意,生成此元数据文件的选项也可以通过 IntelliJ 的 Alt + ENTER
快捷方式在未知属性上使用。