【问题标题】:SpringBoot Failed to bind properties under appSpringBoot在app下绑定属性失败
【发布时间】:2019-11-27 15:34:51
【问题描述】:

我有一个带有 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

我错过了什么?

【问题讨论】:

  • 当应用程序不工作时你是如何运行它的?

标签: spring spring-boot


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 2015-12-08
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多