学无先后,达者为师

网站首页 前端文档 正文

springboot获取自定义json文件数据,并注入spring容器

作者:Denial_learn 更新时间: 2022-05-10 前端文档

json文件

{
  "whiteLj": [
    "/tip/authentication/base/xtgl/bmxy/bmxy",
    "/tip/authentication/base/xtgl/bmxy/bmxy/save",
    "/tip/j_form"
  ]

}

解析json文件,并注入spring容器中

三个注解实现,注入spring容器。
@Component
@EnableConfigurationProperties
@Bean

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

@Component
@EnableConfigurationProperties
public class BmxyJson {

    private String mapName = "whiteLj";

    @Value("classpath:/bmxyJson/Bmxy.json")
    private Resource whiteLj;

    private List jsonlist;

    @Bean
    public List jxJson() throws IOException {

        InputStream inputStream = whiteLj.getInputStream();
        try {
            String jsonsj = IOUtils.toString(inputStream, Charset.forName("UTF-8"));
            //json数据如上,map里面存放一个list数据
            Map> parse = (Map>) JSONObject.parse(jsonsj);
            jsonlist = parse.get(mapName);
            return jsonlist;
        } finally {
            inputStream.close();
        }
    }

}

原文链接:https://blog.csdn.net/Denial_learn/article/details/122415367

栏目分类
最近更新