如何在单例 bean 中重新加载 @RefreshScope bean - BeanFactory.getBean 不工作

问题描述 投票:0回答:0

我需要在运行时更新/刷新某些配置值。 虽然我能够刷新它们,但我无法在单例范围内更新配置 bean。

这是配置bean:

@ConfigurationProperties(prefix = "refreshable")
@RefreshScope
public record RefreshableProperties(
        Optional<String> valueOne,
        Optional<Integer> valueTwo
) {
}

这是一个控制器,它有一个端点来显示当前值和一个刷新它们:

@RestController
@RequiredArgsConstructor
public class MainController {

    private final BeanFactory beanFactory;

    private final ContextRefresher contextRefresher;

    private final RefreshScope refreshScope;

    @GetMapping("/current")
    public String getCurrent() {
        return loadCurrent().toString();
    }

    @GetMapping("/refresh")
    public String refresh() {
        contextRefresher.refresh();//this works - actuator/env now returns refreshed values
        refreshScope.refreshAll();
        return loadCurrent().toString(); // returns old values
    }

    private RefreshableProperties loadCurrent() {
        return beanFactory.getBean(RefreshableProperties.class);
    }

}

在我调用我的刷新端点后,值被正确刷新 - 我可以用

actuator/env
检查,但该方法的响应仍然显示旧值。

如您所见,我尝试了

refreshScope.refreshAll();
以及使用BeanFactory 获取新鲜?我的配置实例。

那么如何正确刷新bean以获得新值呢?

spring-boot spring-cloud
© www.soinside.com 2019 - 2024. All rights reserved.