java - 为什么 @ConfigurationProperties 类的默认值不起作用?

标签 java spring spring-boot

我的 Spring Boot 应用程序中有一个类 typesafe configuration :

@Component
@ConfigurationProperties(prefix = "props")
@Getter
@Setter
public class Properties {
    private String param1 = "val1";
    private String param2 = "val2";
}

后来我尝试在带有注释的 bean 中的字段上使用它:@Value("${props.param1}")

但在应用程序启动时出现以下异常,直到我在 application.properties 中指定自定义属性的值

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'props.param1' in string value "${props.param1}"

如何使 Spring Boot 应用程序使用默认值而不在 application.properties 中指定值?

当我在 application.properties 中键入属性时,我在 IDE 中看到默认值,并且生成的 spring-configuration-metadata.json 内部有一个 defaultValue 文件。我想这个默认值应该与 spring 一起使用,直到我在我的属性文件中覆盖它,但由于未知的原因,我从上面得到了异常。

最佳答案

Later i try to use it on fields in my beans with annotation: @Value("${props.param1}")

这种所谓的“类型安全配置”是一种使用属性的替代方法,允许强类型 bean 管理和验证应用程序的配置。

引入 ConfigurationProperties 的全部目的是不要使用麻烦且容易出错的 @Value。您应该使用 @Autowired 来注入(inject) Properties 配置,而不是使用 @Value:

@Service // or any other Spring managed bean
public class SomeService {
    /**
     * After injecting the properties, you can use properties.getParam1()
     * to get the param1 value, which is defaults to val1
     */
    @Autowired private Properties properties; 

    // Other stuff
}

如果您坚持使用@Value,请先删除Properties类,然后使用@Value("${key:defaultValue}") 表示法如下:

@Value("${props.param1:val1}")

关于java - 为什么 @ConfigurationProperties 类的默认值不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38146207/

相关文章:

java - 如何将字符串日期转换为java.util.Date?

java - Spring MVC请求参数自动映射复杂对象

java - 如何对字符串大小设置验证 = 0 或 min=5,max=10?

java - Spring Boot 可执行 JAR - 布局更改破坏类路径

java - 如何以 JSON 格式显示多对一对象

java - 使用 Tomcat 8.5.9 获取 400 个错误请求

java - Apache 常见邮件 : Exception: Sending the email to the following server failed : smtp. gmail.com:587

java - 获取TableViewer中选定列的列号

java - Cellrenderer 更改单元格背景颜色还更改值格式、对齐方式

java - 为什么我的 thymeleaf 标签是:text don't work