正如标题所说,我正在尝试使用类型安全配置属性来加载DataSourceConfig
对象列表。我有用于 setter/getter 的 lombok
主要应用类注解
@Slf4j
@SpringBootApplication
@EnableConfigurationProperties
public class Application {
配置pojo
@Data
public class DataSourceConfig {
private String key;
private String dbname;
private String dbpath;
}
.yml 文件
tenantdb:
dataSourceConfig:
-
key: default
dbpath: file:eventstore/jdbc/database
dbname: defaultdb
-
key: other
dbpath: file:eventstore/jdbc/other
dbname: dslfjsdf
最后是带有 @ConfigurationProperties 注解的 Spring Configuration 类。
@Configuration
@Profile("hsqldb")
@ImportResource(value = { "persistence-config.xml" })
@Slf4j
@ConfigurationProperties(prefix="tenantdb", locations={"datasources.yml"})
public class HsqlConfiguration {
private List<DataSourceConfig> dataSourceConfig = new ArrayList<>();
@Bean
public List<DataSourceConfig> getDataSourceConfig() {
return dataSourceConfig;
}
通过上面的配置,我得到:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hsqlConfiguration': Could not bind properties to [unknown] (target=tenantdb, ignoreInvalidFields=false, ignoreUnknownFields=true, ignoreNestedProperties=false); nested exception is java.lang.NullPointerException
at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:303)
at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.postProcessBeforeInitialization(ConfigurationPropertiesBindingPostProcessor.java:250)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:408)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initia
我尝试了各种组合。如果我将注释更改为@ConfigurationProperties(prefix="tenantdb.dataSourceConfig")
,我不会收到错误但List<DataSourceConfig>
为空。
帮助!!