【问题标题】:@ConfigurationProperties constructor binding not working in 2.2.0.RC1@ConfigurationProperties 构造函数绑定在 2.2.0.RC1 中不起作用
【发布时间】:2019-10-06 16:12:42
【问题描述】:

我正在尝试新的 Spring Boot 2.2.0.RC1 版本,特别是第 2.8.2 节中描述的新配置属性构造函数绑定功能。构造函数绑定。我建立了一个非常小的项目,其类如下:

@Configuration
@ConfigurationProperties("acme")
public class AppConfig {
    private final String stuff;

    public AppConfig(String stuff) {
        this.stuff = stuff;
    }

    public String getStuff() {
        return stuff;
    }
}

还有这样的 application.yml:

server:
  port: 9000

acme:
  stuff: hello there

我的主要方法在这个类中:

@SpringBootApplication
public class AcmeApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(AcmeApplication.class)
                .logStartupInfo(true)
                .bannerMode(Banner.Mode.CONSOLE)
                .web(WebApplicationType.SERVLET)
                .run();
    }
}

运行应用程序的结果是这样的输出:

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in com.acme.config.AppConfig required a bean of type 'java.lang.String
' that could not be found.


Action:

Consider defining a bean of type 'java.lang.String' in your configuration.

有趣的是,如果我将 AppConfig 类中的代码更改为使用属性绑定,通过删除构造函数、从“stuff”字段中删除“final”修饰符并添加 setStuff(String) 方法,应用程序可以正常启动( setStuff 方法按预期调用)。

我在尝试让构造函数绑定工作时缺少什么?我试过删除@Configuration 注释,添加@EnableConfigurationProperties 注释,添加@ConfigurationPropertiesScan 等等,但是从阅读文档来看,这些东西似乎都不适用于这里。在我看来,它是在尝试注入 Spring bean,而不是构建和注入配置属性对象。这就是为什么我认为删除 @Configuration 注释可能会有所帮助,但它没有任何区别。顺便说一句,我希望这个 AppConfig 是一个 Spring Bean,这样我就可以将它注入到服务类中,例如。

【问题讨论】:

    标签: java spring-boot


    【解决方案1】:

    我错误地查看了里程碑文档。更新的 RC1 文档显示我需要使用 @ImmutableConfigurationProperties 注释以及 @ConfigurationPropertiesScan 注释。

    另见:https://github.com/spring-projects/spring-boot/issues/18543

    【讨论】:

      【解决方案2】:

      进行了简短的研究。这似乎是原因https://github.com/spring-projects/spring-boot/issues/16928#issuecomment-494717209 请查看整个线程以获取更多上下文。 这里是前面提到的问题描述https://github.com/spring-projects/spring-boot/issues/8762#issuecomment-494310988

      【讨论】:

      • 嗯。好的信息,当然,但我的症状不一样。这些问题在应用程序启动后看到空值。我什至无法启动应用程序。另外,我认为他们在 IntelliJ 中运行应用程序的第一个问题。我是从命令行运行的。
      猜你喜欢
      • 2022-11-14
      • 2019-04-30
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多