開發時候在接口沒有提供的時候,可以用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(); } }