spring注解读取json文件

开发时候在接口没有提供的时候,可以用json文件提前模拟接口数据或者自己开发些工具类的网站不想带数据库也可以用本地json数据

实现原理是利用自定义参数注解@Value获取到本地json文件,然后利用Scanner来读取json文件

 

1.service层

复制代码
package com.syp.spring.service;

import java.io.File;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;


@Service
public class TestService {
    @Value(value="classpath:resource/rest.json")
    private  Resource data;    
    
    public String getData(){
        try {
            File file = data.getFile();
            long t0 = System.nanoTime();
            String jsonData = this.jsonRead(file);
            long t1 = System.nanoTime();
            long millis = TimeUnit.NANOSECONDS.toMillis(t1-t0);
            System.out.println(millis +"ms");
            return jsonData;
        } catch (Exception e) {
            return null;
        }
    }
    /**
     *     读取文件类容为字符串
     * @param file
     * @return
     */
      private String jsonRead(File file){
            Scanner scanner = null;
            StringBuilder buffer = new StringBuilder();
            try {
                scanner = new Scanner(file, "utf-8");
                while (scanner.hasNextLine()) {
                    buffer.append(scanner.nextLine());
                }
            } catch (Exception e) {
                
            } finally {
                if (scanner != null) {
                    scanner.close();
                }
            }
            return buffer.toString();
        }

}
复制代码

2.controller层

复制代码
package com.syp.spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.syp.spring.service.TestService;

@Controller
@RequestMapping(value="/syp/spring")
public class TestController {
    
    @Autowired 
    private TestService testService;
    
    @RequestMapping(method=RequestMethod.GET)
    @ResponseBody
    public String test(){
        return testService.getData();
    }
}
复制代码

 

posted @   Brian_Huang  阅读(8913)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
点击右上角即可分享
微信分享提示