Spring 在运行时更改属性文件

Avi*_*gal 5 java spring properties-file spring-boot

我正在使用 Spring Boot 并且我有一个属性文件 p.properties:

p1 = some val1
p2 = some val2
Run Code Online (Sandbox Code Playgroud)

配置类:

@Configuration
@PropertySource("classpath:p.properties")
public class myProperties {

    public myProperties () {
        super();
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用它来访问该属性:

@Value("${p1}")
private String mProperty;
Run Code Online (Sandbox Code Playgroud)

一切都很好。我想从应用程序外部更改 p.properties 文件中的 p1,下次我将使用 mProperty 时,它将包含新值而无需重新启动应用程序。是否可以?

谢谢,阿维

Sha*_*pta 5

您可以简单地使用spring boot actuator. 只需在您maven/gradle configproperty文件中添加执行器依赖项,当您更新文件时,您应该会看到实时重新加载。

注意:您不必重新启动应用程序,但执行器会live reloads自行完成。


amd*_*mdg 1

我认为,在这种情况下,建议将其保存在数据库中,以便可以无缝更改和访问。我们有一个类似的场景,我们将数据库的加密密码保存在属性文件中。连接数据库时,需要解密。我们通过 PropertyPlaceholderConfigurer如下扩展来做到这一点。

public class MyPropertyConfigurer extends PropertyPlaceholderConfigurer{
  protected void convertProperties(Properties props){
        Enumeration<?> propertyNames = props.propertyNames();
        while (propertyNames.hasMoreElements()) {
            String propertyName = (String) propertyNames.nextElement();
            String propertyValue = props.getProperty(propertyName);
            if(propertyName.indexOf("db.password") != -1){
                decryptAndSetPropValue(props,propertyName,propertyValue);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,这仅在加载属性文件时完成一次。