我的 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 内部有一个
文件。我想这个默认值应该与 spring 一起使用,直到我在我的属性文件中覆盖它,但由于未知的原因,我从上面得到了异常。defaultValue
最佳答案
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/