将应用迁移到 Spring Boot 3.0.1 后,无法再从 application.yml
文件加载配置属性。
它不适用于以前没问题的任何类。
以下配置规范开始失败,region
属性未初始化:
@ConfigurationProperties(prefix = "aws")
class AwsConfig {
lateinit var region: Region
var endpointUrl: URI? = null
}
我研究了更现代的实例化属性的方法,并得出以下结论:
package ...
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.bind.ConstructorBinding
import software.amazon.awssdk.regions.Region
@ConfigurationProperties(prefix = "aws")
data class AwsConfig @ConstructorBinding constructor(
val region: Region
)
入口点注释如下:
@SpringBootApplication
@ConfigurationPropertiesScan
class Application
这现在会导致 NPE,让我相信这是一个读取级别的问题。有人遇到过这样的问题吗?
堆栈跟踪的根:
java.lang.IllegalStateException: Failed to load ApplicationContext for [WebMergedContextConfiguration@6fa1dc0c testClass = com.pkg.ApplicationContextTest, ...]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:142)
...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'eventConsumerLauncher' defined in file ... Error creating bean with name 'aws-com.pkg.AwsConfig': Could not bind properties to 'AwsConfig' : prefix=aws, ignoreInvalidFields=false, ignoreUnknownFields=true
at app//org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:798)
...
Caused by: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'aws-com.pkg.AwsConfig': Could not bind properties to 'AwsConfig' : prefix=aws, ignoreInvalidFields=false, ignoreUnknownFields=true
at app//org.springframework.boot.context.properties.ConstructorBound.from(ConstructorBound.java:46)
...
Caused by: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'aws' to com.pkg.AwsConfig
at app//org.springframework.boot.context.properties.bind.Binder.handleBindError(Binder.java:387)
...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.pkg.AwsConfig]: Constructor threw exception
at app//org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:223)
...
Caused by: java.lang.NullPointerException: Parameter specified as non-null is null: method com.pkg.AwsConfig.<init>, parameter region
at com.pkg.AwsConfig.<init>(AwsConfig.kt)
有问题的 application.yml
文件如下所示:
server:
port: -1
spring:
config:
activate:
on-profile: integration
app:
#...
aws:
region: ${AWS_REGION:eu-west-1}
最佳答案
您很有可能受到此影响 issue ,对于 spring-boot 3.0.1
仍然开放。
您可以应用此问题下讨论的解决方法,或者等待可能在 spring-boot 3.0.2
中推出的解决方案。
关于spring-boot - 在 Kotlin 中迁移到版本 3+ 时,Spring Boot 无法再绑定(bind)配置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75069506/