RefreshScope 在重写 PropertySourcesPlaceholderConfigurer 时不起作用

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

根据我的要求,我想在创建 bean 之前更新配置属性。为此,我正在扩展

PropertySourcesPlaceholderConfigurer
并重写 loadProperties 方法。下面是我的代码,效果很好。但是,当我使用 /env 和 /refresh 端点更新属性时,属性不会更新。如果我删除下面的代码,属性就会完美更新。我做错了什么?

@Component
@Slf4j
public class PasswordUpdatePropertyConfigurer extends PropertySourcesPlaceholderConfigurer {
    private ConfigurableEnvironment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
    }

    @Override
    protected void loadProperties(Properties props) {
        
        for (PropertySource<?> propertySource : environment.getPropertySources()) {
            if (propertySource instanceof EnumerablePropertySource) {
                String[] propertyNames = ((EnumerablePropertySource) propertySource).getPropertyNames();
                for (String propertyName : propertyNames) {
                    String configValue = String.valueOf(propertySource.getProperty(propertyName));
                    String secretValue = configValue;
                    if (StringUtils.isNotEmpty(configValue) && configValue.startsWith("password")) {
                            secretValue = configValue.replace("password","niti");  
                    }
                    if (!props.containsKey(propertyName)) {
                        props.setProperty(propertyName, secretValue);
                    }
                }
            }
        }
    }
}

spring spring-cloud spring-boot-actuator spring-bean spring-context
1个回答
0
投票

我们面临着同样的问题。我们需要使用 PropertySourcesPlaceholderConfigurer 管理一些 yml 文件,当我尝试使用执行器重新加载属性时,它不起作用。 Spring日志显示读取了新属性,但后来我意识到它们没有注入@Value变量中。只有当我评论该代码时,注入才会顺利进行。

© www.soinside.com 2019 - 2024. All rights reserved.