首页 > 解决方案 > @ConfigurationProperites 升级到 Spring Cloud Hoxton.SR7 后未绑定到属性源

问题描述

我有一个@ConfigurationProperties不再绑定到 YML 属性源的类,该类在升级到 Hoxton.SR7 后通过 Spring Cloud Config 得到解决。此代码使用最新的 Spring Boot 2.2.9.RELEASE 的 Hoxton.SR4 可以正常工作。现在,我的属性未绑定,当我尝试引用它们时,我收到了 NPE。以下是我的代码的快照:

@Configuration
public class MyConfiguration {

  @Bean
  public MyPropertiesBean myPropertiesBean() {
    return new MyPropertiesBean(); 
  }

}
@ConfigurationProperties(prefix = "com.acme.properties")
@Validated
public class MyPropertiesBean {
  ...
}

src/main/resources/META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.acme.MyConfiguration

有什么想法为什么@ConfigurationProperties在将 Spring Cloud 升级到 Hoxton.SR7 后我的课程没有绑定?

标签: spring-bootspring-cloudspring-cloud-config

解决方案


您正在混合两种绑定属性的方式:类和方法。

使用方法和@Bean注解:

@Configuration
public class MyConfiguration {

  @Bean
  @ConfigurationProperties(prefix = "com.acme.properties")
  @Validated
  public MyPropertiesBean myPropertiesBean() {
    return new MyPropertiesBean(); 
  }

}

MyPropertiesBean这将在应用程序上下文中创建并存储它以供您注入。

类级别的 bean 声明还为您创建了一个 bean:

@Configuration
@ConfigurationProperties(prefix = "com.acme.properties")
@Validated
public class MyPropertiesBean {
  ...
}

这也将存储一个 bean。

虽然,当您尝试注入时应该会遇到运行时错误,MyPropertiesBean因为在您的情况下,现在有两个相同类型的 bean,而 Spring 无法仅使用该类型解析。


推荐阅读