Java 将一些 JSON 文件加载到 Spring Boot 应用程序中的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34277392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to load some JSON files into a Spring Boot application
提问by diamah
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).
我将要创建一个 Rest webservice 应用程序,我需要在应用程序启动时加载作为参数传递的文件夹中存在的所有 JSON 文件(在 application.yml aprii 中),以便稍后在 webservices 的方法中使用它们作为bean 列表(每个 JSON 文件对应一个 bean)。
A sample to further explain my requirements:
进一步解释我的要求的示例:
application.yml:
应用程序.yml:
json.config.folder: /opt/my_application/json_configs
MyApplication.java:
我的应用程序.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 Files having this structure:
具有此结构的 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
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.javathat will contain JSON file infos a priori:
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;
}
}
And another class called Operator.java containing all operator infos.
另一个名为 Operator.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)?
有没有一种方法可以ContextOperatorBean
在应用程序启动时初始化包含所有 JSON 文件信息的对象列表,并在我的 Web 服务方法(RestAPI.java 类)中使用它们?
采纳答案by kryger
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.
注意:忽略了处理失败或意外情况以及一些实现细节。
Then @Autowire
it in your controller and call getMatchingOperators()
to filter only matching entries.
然后@Autowire
它在您的控制器中并调用getMatchingOperators()
以仅过滤匹配的条目。
回答by Arvind Kumar
This may not be answering the question directly but will help in reading any JSON to java object in spring boot easily.
这可能不是直接回答问题,但有助于在 Spring Boot 中轻松读取任何 JSON 到 Java 对象。