Java Spring Boot: Reload config without spring cloud config server

拟墨画扇 提交于 2019-12-02 03:12:05

There is quite a discussion on that: how to refresh properties without any configuration server. There is a Dave Syer post on that here which brings some light - but still isn't self-explanatory.

The most natural approach for spring-boot/-cloud would be following (as discussed on spring-cloud-config github):

@Component
@ConfigurationProperties("ignored")
@RefreshScope
public class Config {
    private List<String> path;

    public List<String> getPath() {
        return path;
    }

    public void setPath(List<String> path) {
        this.path = path;
    }
}

This doesn't work due to some proxy issues between @RefreshScope and @ConfigurationProperties - both annotations result in bean proxies with are at odds with each other.

Therefore I started looking at it from a spring perspective. The propertySources are accessible through Environment so you can access and modify them by

final String propertySourceName = "externalConfiguration"; 
// name of propertySource as defined by 
// @PropertySource(name = "externalConfiguration", value = "${application.config.location}")
ResourcePropertySource propertySource = new ResourcePropertySource(propertySourceName, new FileSystemResource(file));
MutablePropertySources sources = ctx.getEnvironment().getPropertySources();
sources.replace(propertySourceName, propertySource);

My use case was based on "user editing the file" so the properties refreshed was based on the FileSystemWatcher, which mutated the propertySources. For the sources to be correctly ingested by the configuration bean, the scope of the bean needed to be a prototype - to be correctly rebuilt on every invocation.

The complete example is available as a gist. No config server is included whatsoever. Hope that helps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!