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

本文介绍如何使用Spring Boot将JSON文件中的配置数据加载到应用程序中,并通过注解方式将这些配置注入到Spring容器。主要实现了从classpath路径下读取JSON文件,解析JSON数据并获取指定键值对应的列表。

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<String> 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<String,List<String>> parse = (Map<String,List<String>>) JSONObject.parse(jsonsj);
            jsonlist = parse.get(mapName);
            return jsonlist;
        } finally {
            inputStream.close();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值