小编典典

将一些JSON文件加载到Spring Boot应用程序中的最佳方法

spring-boot

我将要创建一个Rest Web服务应用程序,我需要在应用程序启动时加载作为参数传递的文件夹中存在的所有JSON文件(在application.yml
aprii中),以便以后在Webservices方法中使用它们bean列表(每个JSON文件都对应一个bean)。

一个样本进一步解释我的要求:

application.yml

json.config.folder: /opt/my_application/json_configs

MyApplication.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的类包含所有操作员信息。

是否有一种方法可以ContextOperatorBean在应用程序启动时初始化包含所有JSON文件信息的对象列表,并在我的Web服务方法(RestAPI.java类)中使用它们?


阅读 470

收藏
2020-05-30

共1个答案

小编典典

不知道以下的天真的实现是否满足“最佳”的标准,但是您可以创建一个新的服务来处理这种责任,例如:

@Service
public class OperatorsService {

    @Value("${json.config.folder}")
    String jsonConfigFolder;

    List<ContextOperatorBean> operators = new ArrayList<>();

    @PostConstruct
    public void init() throws IOException {
        ObjectMapper jsonMapper = new ObjectMapper();
        for (File jsonFile : getFilesInFolder(jsonConfigFolder)) {
            // deserialize contents of each file into an object of type
            ContextOperatorBean operator = jsonMapper.readValue(jsonFile, new TypeReference<List<ContextOperatorBean>>() {});
            operators.add(operator);
        }
    }

    public List<ContextOperatorBean> getMatchingOperators(String context) {
        return operators.stream().filter(operator -> checkIfMatches(operator, context)).collect(Collectors.toList());
    }

    private boolean checkIfMatches(ContextOperatorBean operator, String context) {
        // TODO implement
        return false;
    }

    private File[] getFilesInFolder(String path) {
        // TODO implement
        return null;
    }
}

注意:忽略了处理失败或意外情况以及一些实施细节。

然后@Autowire在控制器中调用它并getMatchingOperators()仅过滤匹配的条目。

2020-05-30