【发布时间】: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