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