作为标题所述,我正在尝试使用Typesafe Configuration Properties来加载
主要应用程序类注释
配置POJO
最后,使用@ConfigurationProperties注释的Spring配置类。
使用上述配置,我得到:
我尝试了各种组合。如果我将注释更改为
帮帮我!!
DataSourceConfig
对象列表。我有用于setter/getters的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
@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>
为空。帮帮我!!
@ConfigurationProperties(prefix="tenantdb", locations={"datasources.yml"})
并且它按预期工作,唯一的问题是我不想添加 lombok,所以使用了常规的 setter/getters。此外,当我将 yml 文件放置在 /config 位置时遇到了问题,但是当我将其放置在src/main/resources
中时,它开始正常工作。 - Nenad Bozic@ConfigurationProperties(prefix="tenantdb", locations={"datasources.yml"})
处时,遇到了NPE错误:( - 在此位置at org.springframework.boot.bind.RelaxedDataBinder.extendCollectionIfNecessary(RelaxedDataBinder.java:248)
。 - Raghu@ConfigurationProperties
bean 应该是一个简单的 pojo。你添加在它上面的所有这些注解对我来说似乎都不是正确的位置。你在DataSourceConfig
上使用的@Bean
明显是错误的。请将仅配置部分移动到一个只有@ConfigurationProperites
的 bean 中。Lombok 是被支持的。 - Stephane NicollTenantDbProperties
。这个类只需要添加@Component
和@ConfigurationProperties(prefix="tenantdb", locations={"datasources.yml"})
注释,并且它应该是一个简单的POJO对象,就像@StéphaneNicoll建议的那样。除此之外,还需要添加HsqlConfiguration
和其他配置信息,以及在属性所在的包上进行组件扫描。 - Nenad Bozic