时间: 2020-11-26|75次围观|0 条评论

以前有一篇文章专门讲了怎么加载classpath路径的资源文件:

https://blog.csdn.net/w605283073/article/details/89410507

 

最近接触到另外一种比较新奇的方式。

 

资源:

获取Spring资源文件的新姿势插图

 

加载方式:

package com.chujianyun.web;

import com.alibaba.fastjson.JSON;
import com.chujianyun.libs.json.Cat;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.nio.charset.Charset;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {Application.class})
public class WebTest {

    /**
     * 第一种方式
     */
    @Value("${classpath:json/cat.json}")
    private ClassPathResource catJson;

    @Test
    public void testGetResource() throws IOException {
        String cat = IOUtils.toString(catJson.getInputStream(), Charset.forName("UTF-8"));
        Cat catObj = JSON.parseObject(cat, Cat.class);
        Assert.assertEquals("tom",catObj.getName());
    }

    /**
     * 第二种方式
     */
    @Test
    public void testGetResource2() throws IOException {
        Resource resource = new ClassPathResource("json/cat.json");
        String cat = IOUtils.toString(resource.getInputStream(), Charset.forName("UTF-8"));
        Cat catObj = JSON.parseObject(cat, Cat.class);
        Assert.assertEquals("tom",catObj.getName());
    }

    @Test
    public void testGetResource3() throws IOException {
        Cat catObj = getJsonObject("json/cat.json",Cat.class);
        Assert.assertEquals("tom",catObj.getName());
    }

    /**
     * tip:可以封装到单独的工具类中
     */
    private <T> T getJsonObject(String resourcePath, Class<T> clazz) throws IOException {
        Resource resource = new ClassPathResource(resourcePath);
        String cat = IOUtils.toString(resource.getInputStream(), Charset.forName("UTF-8"));
        return JSON.parseObject(cat, clazz);
    }
}

当然这种方法可以封装成独立的ResourceUtil工具类,输入资源路径和类型,返回对应的JSON对象。

如果觉得本文对你有帮助,欢迎点赞评论,欢迎关注我,我将努力创作更多更好的文章。

原文链接:https://blog.csdn.net/w605283073/article/details/89648089

本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《获取Spring资源文件的新姿势
   

还没有人抢沙发呢~