@ConfigurationProperties构造函数绑定在 2.2.0.RC1 中不起作用



我正在尝试新的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;
}
}

以及像这样的应用程序.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,这样我就可以将其注入到 Service 类中。

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

另请参阅:https://github.com/spring-projects/spring-boot/issues/18543

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

最新更新