首页 > 解决方案 > Spring boot - Application.properties 中的用户定义变量

问题描述

我正在尝试在 application.properties 文件中添加自定义变量。当我添加时,IDE(Eclipse 2019-06 (4.12.0) 和 Spring Tool Suite 4.3.1)显示黄色警告“abc.def 是未知属性”。

该问题类似于Application.properties 中的 Spring boot-custom variables。我尝试了@StephaneNic​​oll 在答案中给出的方法。它仍然显示相同的警告。其实我在Eclipse中打开了项目https://github.com/snicoll-demos/spring-boot-configuration-binding 。它仍然给出相同的警告。还有什么我需要做的吗?

这是一个小烦恼。但想摆脱它。

标签: springspring-bootspring-mvcspring-data

解决方案


您必须添加spring-boot-configuration-processor到您的项目中:

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

然后使用注释@ConfigurationProperties及其前缀创建您的属性类,例如:

@Data
@ConfigurationProperties(prefix = "abc")
@Validated
public class AbcProperties {

    /**
     * Description of the property 'def'.
     */
    @NotNull private Long def = 0L;  // <- default value of the property

    // other props...
}

然后启用它:

@SpringBootApplication
@EnableConfigurationProperties(AbcProperties.class)
public class AbcApplication {
    //...
}

然后重建你的项目。在这些步骤之后,IDE 将正确地看到您的道具。

更多信息:


推荐阅读