前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >获取Spring资源文件的新姿势

获取Spring资源文件的新姿势

作者头像
明明如月学长
发布2021-08-31 15:50:28
3750
发布2021-08-31 15:50:28
举报
文章被收录于专栏:明明如月的技术专栏

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

https://cloud.tencent.com/developer/article/1870486

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

资源:

加载方式:

代码语言:javascript
复制
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 getJsonObject(String resourcePath, Class 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对象。

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

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/04/28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档