Spring在运行时更改属性文件

6

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

p1 = some val1
p2 = some val2

配置类:

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

    public myProperties () {
        super();
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

我正在使用这个来访问属性:
@Value("${p1}")
private String mProperty;

一切运行良好。 我希望能在应用程序外部更改p.properties文件中的p1,并且下一次使用mProperty时,它将包含新值而无需重新启动应用程序。 这可能吗?

谢谢, Avi


更改属性文件是否是生产代码的一部分,还是您只想在开发环境中进行? - Shanu Gupta
这篇文章可能会对你有所帮助:http://jeroenbellen.com/manage-and-reload-spring-application-properties-on-the-fly/ - Shanu Gupta
@ShanuGupta 这不是代码的一部分。我想要直接从文件中进行更改。 - Avi Elgal
这是生产代码的一部分吗? - Shanu Gupta
1
这不是生产代码的一部分。 - Avi Elgal
你指的是应用程序之外的意思是什么? - Shanu Gupta
3个回答

6
你可以简单地使用spring boot actuator。 只需在你的maven/gradle配置文件中添加actuator依赖项,当你更新属性文件时,应该看到实时重新加载。
注意:你不需要重新启动应用程序,但actuator将自行进行实时重新加载

2
如果您想在运行时更改属性而不想重新启动服务器,请按以下步骤操作:
1. Application.properties
``` app.name=xyz management.endpoints.web.exposure.include=* ```
2. 在pom.xml中添加以下依赖项:
``` org.springframework.boot spring-boot-starter-actuator org.springframework.cloud spring-cloud-context 2.0.1.RELEASE ```
3. 将application.properties放置在config文件夹中。config文件夹必须位于您运行jar的位置。
4. 添加ApplcationProperties.java
``` @RefreshScope @Component @ConfigurationProperties(prefix = "app") public class ApplcationProperties { private String name; //getter and setter } ```
5. 编写ApplicationController.java并注入ApplcationProperties
``` @Autowired ApplcationProperties applcationProperties;
@RestController public class ApplicationController { @GetMapping("/find") String getValue() { return applicationProperties.getName(); } } ```
6. 运行Spring Boot应用程序
7. 从浏览器调用localhost:XXXX/find
输出:xyz
8. 将application.properties中的值从xyz更改为abc
9. 使用postman发送put/options请求到localhost:XXXX/actuator/refresh
注意:此请求应为PUT/OPTIONS
10. 从浏览器调用localhost:XXXX/find
输出:abc

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);
            }
        }
    }
}

但是,这只在加载属性文件时执行一次。


如果我们在运行时更改了加密密码,那么我们需要重新启动应用程序吗? - Khwaja Sanjari
1
如果您在运行时更改属性文件中的密码,则需要重新启动。如答案所指出的那样,属性文件仅在应用程序启动时加载和读取一次。 - amdg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接