将一些 JSON 文件加载到 Spring Boot 应用程序中的最佳方式
2022-09-02 01:49:18
我即将创建一个 Rest Webservice 应用程序,我需要加载所有 JSON 文件,这些文件都存在于作为参数传递的文件夹中(在 application.yml a priori 中),在应用程序启动时,稍后在 Web 服务方法中将它们用作 bean 列表(每个 JSON 文件对应于一个 Bean)。
进一步解释我的要求的示例:
application.yml:
json.config.folder: /opt/my_application/json_configs
我的申请.java:
package com.company;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
具有以下结构的 JSON 文件:
{
"key":"YYYYY",
"operator_list":[
{
"name":"operator1",
"configs":{
"id":"XXXXX1",
"path":"xxxx2"
}
},
{
"name":"operator2",
"configs":{
"id":"XXXXX1",
"passphrase":"xxxx2",
"user_id":"XXXX3",
"password":"XXXXX"
}
},
{
"name":"operator3",
"configs":{
"user_id":"XXXXX1"
}
}
]
}
RestAPI.java
@RestController
@RequestMapping("/my_app_url")
@PropertySource(value={"classpath:application.yml"})
public class RestAPI {
//Some fields
....
//Some methods
....
//Method that return operator list of a given context (correspond to the field "key" of the json file)
@RequestMapping("/getOperatorList")
public List<Operator> getOperatorList(@RequestParam(value = "context", defaultValue = "YYYYY") String context) throws Exception{
List<Operator> result = null;
//Here, i need to loop the objects , that are supposed to be initialized during application startup
//(but i I do not know yet how to do it) with data from JSON files
//to find the one that correspond to the context in parameter and return its operator list
return result;
}
}
ContextOperatorBean.java将先验地包含 JSON 文件信息:
package com.company.models;
import java.util.List;
public class ContextOperatorBean {
String key;
List<Operator> operator_list;
public ContextOperatorBean() {
}
public ContextOperatorBean(String key, List<PaymentMethod> operator_list) {
this.key = key;
this.operator_list = operator_list;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<Operator> getOperator_list() {
return operator_list;
}
public void setOperator_list(List<Operator> operator_list) {
this.operator_list = operator_list;
}
}
另一个名为 Operator 的类.java包含所有运算符信息。
有没有一种方法可以在应用程序启动时初始化包含所有 JSON 文件信息的对象列表,并在我的 Web 服务方法(RestAPI.java 类)中使用它们?ContextOperatorBean