IILeeのBlog

IILeeのBlog

解决 Spring 配置文件中 Can not resolve configuration property 'xxx'

338
2021-02-21
解决 Spring 配置文件中 Can not resolve configuration property 'xxx'

1 现象

在spring boot的配置文件中定义配置信息,如在application.yml中定义remoteServer属性。

application.yml:

remoteServer: "xxx"

复制代码将会有以下提示信息:

Cannot resolve configuration property 'remoteServer' 

2 解决方法

为了使IntelliJ IDEA知道自定义Spring Boot属性,可以在项目中定义Spring Boot配置元数据。

2.1 添加配置注释处理器到类路径中

如果可以为属性使用@ConfigurationProperties注释的类,则可以将Spring Boot配置注释处理器添加到类路径中,并且IntelliJ IDEA将在 target 或者 out 生成配置元数据:

Maven:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Gradle:

implementation 'org.springframework.boot:spring-boot-configuration-processor'

2.2 创建配置元数据文件

创建 src/main/resources/META-INF/spring-configuration-metadata.json文件:

{
  "properties": [
      "name": "remoteServer",
      "type": "java.lang.String",
      "description": "xxxx."
  ]
}

2.3 使配置生效

在构建系统(Maven / Gradle)的IntelliJ IDEA工具窗口中,单击“刷新”按钮。
从菜单中选择 build > Rebuild Project
如果仍然出现警告,则可以尝试重新启动IDE。 选择 File > Invalidate Caches / Restart,然后单击 Invalidate and Restart

3 引用

参考文章:原文地址