将一些JSON文件加载到Spring Boot应用程序的最佳方法 [英] Best way to load some JSON files into a Spring Boot application

查看:179
本文介绍了将一些JSON文件加载到Spring Boot应用程序的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm about to create a Rest webservice application, and I need to load all JSON files that exist in a folder passed as parameter (in application.yml a priori), on application startup, to use them later in the methods of webservices as a list of beans (every JSON file corresponds to a bean).

进一步解释我的要求的示例:

A sample to further explain my requirements:

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文件:

JSON Files having this structure:

    {  
   "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文件信息:

ContextOperatorBean.java that will contain JSON file infos a priori:

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的类包含所有运营商信息。

And another class called Operator.java containing all operator infos.

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

Is there a method to initialize a ContextOperatorBean object list that contain infos of all JSON files, on application startup, and use them in my webservice methods (RestAPI.java class)?

推荐答案

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

No idea if the following naïve implementation satisfies the criterium of being "best", but you could create a new service that deals with this responsibility, for example:

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

注意:遗漏处理失败或意外情况和一些实现细节。

NOTE: left out handling failures or unexpected conditions and some implementation details.

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

Then @Autowire it in your controller and call getMatchingOperators() to filter only matching entries.

这篇关于将一些JSON文件加载到Spring Boot应用程序的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆