如标题所示,我正在尝试使用Typesafe Configuration Properties加载DataSourceConfig
对象的列表。我有二传手的 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>
为空。帮助!!
最佳答案
您应该将配置属性用作仅具有getter和setter的简单POJO,并使用单独的HsqlConfiguration
注入(inject)此属性。
像这样的东西:
@Component
@ConfigurationProperties(prefix="tenantdb", locations={"datasources.yml"})
public class TenantDbProperties {
//DataSourceConfig is POJO with key, dbpath and dbname
private List<DataSourceConfig> dataSourceConfigs;
public List<DataSourceConfig> getDataSourceConfigs(){
return dataSourceConfigs;
}
public void setDataSourceConfigs(List<DataSourceConfig> dataSourceConfigs){
this.dataSourceConfigs = dataSourceConfigs;
}
}
并在单独的类中将此属性注入(inject)为:
@Configuration
@Profile("hsqldb")
@ImportResource(value = { "persistence-config.xml" })
@Slf4j
public class HsqlConfiguration {
@Autowired
private TenantDbProperties tenantDbProperties;
//code goes here where you can use tenantDbProperties.getDataSourceConfigs()
}