首页 > 解决方案 > 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

我错过了什么?

标签: springspring-boot

解决方案


原因在于初始化的顺序。您没有填写 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。


推荐阅读