springboot@ConfigurationProperties列表重载不起作用



我有一个问题,当这个配置更改时,我用@ConfigurationProperties配置,配置对象没有更改。配置为列表。如果add-config,则列表会更改,但如果remove-config,则列表不会更改。


@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中。

请确保属性文件中的属性和类(具有给定前缀(具有正确的绑定。

请确保在更改类文件和属性文件时正确编译。

使类实现可序列化(如果需要(。

如果您在验证后仍然面临问题,请告诉我。

最新更新