[英]Springboot @ConfigurationProperties load list from yaml not working
[英]springboot @ConfigurationProperties list reload not work
我有一个问题,当此配置更改时,我使用 @ConfigurationProperties 进行配置,但配置对象未更改。 配置是列表。 如果添加配置列表更改,但如果删除配置列表不更改。
@ConfigurationProperties(prefix = "zzzz.kafka")
public class ToadDynamicProps {
private List<String> bootstrapServers;
public ToadDynamicProps() {
System.out.println(bootstrapServers + " ===============");
}
public List<String> getBootstrapServers() {
return bootstrapServers;
}
public void setBootstrapServers(List<String> bootstrapServers) {
this.bootstrapServers = bootstrapServers;
}
}
我自己实现监听器是这样的:
@Override
public void onConfigChange(Map<String, String> properties) {
if (log.isDebugEnabled()) {
log.debug("ToadContextRefresher invoked, changed keys: {}", properties.keySet());
}
// update environment
MutablePropertySources targetSources = context.getEnvironment().getPropertySources();
CompositePropertySource compositeSource = (CompositePropertySource) targetSources.get(BOOTSTRAP_PROPERTY_SOURCE_NAME);
CompositePropertySource newBootstrapSource = new CompositePropertySource(BOOTSTRAP_PROPERTY_SOURCE_NAME);
//TODO fix
if(null == compositeSource) {
return ;
}
// shallow copy for non-toad propertySource, swap toad propertySource
for (PropertySource part : compositeSource.getPropertySources()) {
if (Objects.equals(part.getName(), TOAD_PROPERTY_KEY)) {
log.debug("Found toad property source in environment, update it...");
Map<String, Object> oldProperties = ((MapPropertySource) part).getSource();
Map<String, Object> newProperties = new HashMap<>(oldProperties);
newProperties.putAll(properties);
MapPropertySource newToadSource = new MapPropertySource(TOAD_PROPERTY_KEY, newProperties);
newBootstrapSource.addPropertySource(newToadSource);
}
newBootstrapSource.addPropertySource(part);
}
targetSources.replace(BOOTSTRAP_PROPERTY_SOURCE_NAME, newBootstrapSource);
Set<String> changedKeys = properties.keySet();
this.context.publishEvent(new EnvironmentChangeEvent(context, changedKeys));
this.scope.refreshAll();
}
确保类 (ToadDynamicProps) 应该使用@Configuration
进行注释,或者您需要在主 Spring 应用程序类中提供@EnableConfigurationProperties(ToadDynamicProps.class)
以将属性绑定到 POJO。
确保属性文件中的属性和类(具有给定前缀)具有正确的绑定。
确保在更改时正确编译类文件和属性文件。
使您的类实现可序列化(如果需要)。
如果您在验证这一点后仍然遇到问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.