spring - SpringBoot在app下绑定属性失败
问题描述
我有一个带有 gradle 的 SpringBoot 2.1.7.RELEASE 项目。当我尝试使用 @ConfigurationProperties 时出现错误
我尝试绑定的属性存在于我的 application-default.properties 中,如果我使用 Itellij 运行项目,我可以看到该属性已被提取到我的组件中。
如果我启用 @EnableConfigurationProperties 我得到一个错误。
我的应用程序-default.properties
app.forwarding-endpoint=localhost:8080
我的 AppProperties.java
@ConfigurationProperties(prefix = "app", ignoreUnknownFields = false)
@Validated
@Data
public class AppProperties {
@NotBlank
@Pattern(regexp = "^(.+):\\d+$")
private String forwardingEndpoint;
}
我的应用程序.java
@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application .class, args);
}
}
我正在使用该属性的组件:
public MyComponent(@Value("${app.forwarding-endpoint}") String forwardingEndpoint) {
log.info("Forwarding endpoint {}", forwardingEndpoint);
}
我得到的错误是:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'app' to com.config.AppProperties failed:
Property: app.forwardingEndpoint
Value: null
Reason: must not be blank
我错过了什么?
解决方案
原因在于初始化的顺序。您没有填写 AppProperties,而是开始在组件中使用它。您还需要将此类注释为组件,但从架构的角度来看,这不是一个好方法。
@ConfigurationProperties 的概念对于 Spring 来说是非常原始的,如果没有一些操作,你将很难强制它正常工作。我提出了一个简单的“技巧”(或“另一种方法”):
@Data
public class AppProperties {
@NotBlank
@Pattern(regexp = "^(.+):\\d+$")
private String forwardingEndpoint;
}
(我认为@validated 的位置不在实体/DO 中)。
并在您的 @Configuration 下一个代码中放置:
@Bean
@ConfigurationProperties(prefix = "app", ignoreUnknownFields = false)
public AppProperties setAppProperties() {
return new AppProperties();
}
接下来,您可以在任何组件中注入 AppProperties bean。
推荐阅读
- java - 如何使用 JsonPath 从 json 中找到给定键的值?
- excel - VBA复制粘贴循环并转到下一个可用单元格
- ios - 当从 Dft tableview 转回来时,Comp tableview 被复制了
- python - 如何将所有 CSV 文件从谷歌云存储位置读取到单个熊猫数据框中?
- java - Spring 方面,在受保护的重载方法上的切入点
- reactjs - SSL socket.io 客户端未收到服务器响应
- python-3.x - python kivy,为什么我的带有“on_keyboard_down”的“输入”按钮不起作用
- windows-7 - Windows 7 上的 CefSharp TouchInput
- r - 从向量中选择行并在 R 的文件夹中找到相关文件
- apache-kafka-streams - KafkaStreams:源主题的任务数和正则表达式