我的 application.properties 文件有问题,它不是我的 war 文件的一部分。我想创建一个可以在运行时更改 application.properties 值的应用程序。我的属性文件将是我们将在服务中使用的 bean。
以下 PoC 类别:
@Configuration
@Slf4j
public class ServiceReaderConfiguration {
@Bean
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
ServiceOutputProperties serviceProperties() {
log.info("create serviceProperties");
return new ServiceOutputProperties();
}
@Bean
ServiceOutput serviceOutput() {
log.info("create serviceOutput");
return new ServiceOutput(serviceProperties());
}
}
服务属性
@Configuration
@ConfigurationProperties(prefix = "prefix")
@Setter
@Getter
public class ServiceOutputProperties {
private int param;
}
服务输出属性
@Slf4j
public class ServiceOutput {
private ServiceOutputProperties serviceOutputProperties;
public ServiceOutput(ServiceOutputProperties serviceOutputProperties) {
log.info("creating serviceOutputProperties");
this.serviceOutputProperties = serviceOutputProperties;
}
public int printValueFromFile() {
int param = serviceOutputProperties.getParam();
return param;
}
}
Controller
@RestController
@RequestMapping("/api")
public class ControllerConfiguration {
@Autowired
private ServiceOutput serviceOutput;
@GetMapping("/print")
public ResponseEntity<Integer> postValueFromPropertiesFile() {
return ResponseEntity.ok(serviceOutput.printValueFromFile());
}
}
应用程序属性
prefix.param=2
放在 Catalina 文件中的 XML 文件
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Environment name="spring.config.location"
value="file:/home/marcin/tomcat/application.properties"
type="java.lang.String"/>
</Context>
我正在构建没有我想在运行时修改的应用程序属性文件的 war 包。包正在 tomcat 上部署。我想要实现的是修改属性文件并在运行时使用 Controller 显示文件中的更改值,而无需重新加载应用程序。
在此先感谢您的帮助。
最佳答案
您可以使用 spring cloud 的刷新范围功能来实现它,考虑以下情况:
@ConfigurationProperties(prefix = "prefix")
@PropertySource("path to properties file, you can inject it as property ${spring.config.location}")
@RefreshScope
public class ServiceOutputProperties {
private int param;
//getters & setters
}
稍后您可以通过两种方式像这样刷新 beans:通过向端点 /actuator/refresh
发送 POST 请求(如果您使用的是 spring-actuator)或通过注入(inject) RefreshScope
bean 并调用 refreshAll()
方法(或 refresh(String name)
如果你想刷新单个 bean)。
您可以使用 WatchService API创建监听器,它将在每次文件修改时调用上述方法之一。
刷新范围功能包含在 spring-cloud-context 中所以我相信它足够轻
关于java - 如何在运行时重新加载不属于 jar 的 application.properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53762482/