【发布时间】:2015-03-19 08:38:02
【问题描述】:
正如标题所说,我正在尝试使用Typesafe Configuration Properties 加载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> 是空的。
求助!!
【问题讨论】:
-
我的配置属性用
@Component注解并且在组件扫描时被填满,你试过吗?还有两件事,datasources.yml位于哪里,为什么getDataSourceConfig被注释为 bean? -
datasources.yml位于类路径根目录中。getDataSourceConfig被注释为 bean,以便我也可以将其注入其他地方。 -
我尝试使用您的代码,创建了测试,并按预期得到了 2 个
DataSourceConfig的列表。唯一的问题是它们是空的(key、dbname和dbpath有null。我在那个类上提供了设置器,它绑定得很好,可能是这样吗? -
@ConfigurationPropertiesbean 是一个简单的 pojo。你在上面添加的所有这些注释对我来说似乎都是错误的地方。你在DataSourceConfig上的@Bean绝对是错误的。请仅将配置部分移动到仅带有@ConfigurationProperites的 bean。支持龙目岛。 -
正如我在第一条评论中所说,您可能应该制作
TenantDbProperties,它们只是@Component和@ConfigurationProperties(prefix="tenantdb", locations={"datasources.yml"}),并且是@StéphaneNicoll 建议的简单pojo,并且具有HsqlConfiguration以及其他配置和组件扫描在属性所在的包上
标签: java spring spring-boot configurationproperty