前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot 系列-资源访问

SpringBoot 系列-资源访问

作者头像
用户4044670
发布2020-03-02 10:15:00
5890
发布2020-03-02 10:15:00
举报
文章被收录于专栏:安徽开发者圈

当我们创建一个 SpringBoot web 应用时,有时候需要从 classpath 去加载一些文件,这里记录下在 war 和 jar 两种不同文件格式下加载文件的解决方案。

The ResourceLoader

在 Java 中 ,我们可以使用当前线程的 classLoader 去尝试加载文件,但是 Spring Framework 为我们提供了更加优雅的解决方案,例如 ResourceLoader。

使用 ResourceLoader 时,我们只需要使用 @Autowire 自动注入 ResourceLoader,然后调用 getResource(“somePath”) 方法即可。

在Spring Boot(WAR)中从资源目录/类路径加载文件的示例

代码语言:javascript
复制
@Service("geolocationservice")
public class GeoLocationServiceImpl implements GeoLocationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(GeoLocationServiceImpl.class);
    private static DatabaseReader reader = null;
    private ResourceLoader resourceLoader;
    @Autowired
    public GeoLocationServiceImpl(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    public void init() {
        try {
            LOGGER.info("GeoLocationServiceImpl: Trying to load GeoLite2-Country database...");
            Resource resource = resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");
            File dbAsFile = resource.getFile();
            // Initialize the reader
            reader = new DatabaseReader
                        .Builder(dbAsFile)
                        .fileMode(Reader.FileMode.MEMORY)
                        .build();
            LOGGER.info("GeoLocationServiceImpl: Database was loaded successfully.");
        } catch (IOException | NullPointerException e) {
            LOGGER.error("Database reader cound not be initialized. ", e);
        }
    }
    @PreDestroy
    public void preDestroy() {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                LOGGER.error("Failed to close the reader.");
            }
        }
    }
}

从 SpringBoot FatJar 中加载资源

如果我们想从 Spring Boot JAR 中的类路径加载文件,则必须使用 resource.getInputStream() 方法将其作为 InputStream 检索。如果尝试使用resource.getFile(),则会收到错误消息,因为 Spring 尝试访问文件系统路径,但它无法访问 JAR 中的路径。

代码语言:javascript
复制
@Service("geolocationservice")
public class GeoLocationServiceImpl implements GeoLocationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(GeoLocationServiceImpl.class);
    private static DatabaseReader reader = null;
    private ResourceLoader resourceLoader;

    @Inject
    public GeoLocationServiceImpl(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostConstruct
    public void init() {
        try {
            LOGGER.info("GeoLocationServiceImpl: Trying to load GeoLite2-Country database...");
            Resource resource = resourceLoader.getResource("classpath:GeoLite2-Country.mmdb");
            InputStream dbAsStream = resource.getInputStream(); // <-- this is the difference
            // Initialize the reader
            reader = new DatabaseReader
                        .Builder(dbAsStream)
                        .fileMode(Reader.FileMode.MEMORY)
                        .build();
            LOGGER.info("GeoLocationServiceImpl: Database was loaded successfully.");
        } catch (IOException | NullPointerException e) {
            LOGGER.error("Database reader cound not be initialized. ", e);
        }
    }

    @PreDestroy
    public void preDestroy() {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                LOGGER.error("Failed to close the reader.");
            }
        }
    }
}

▐ 文章来源: 磊叔授权分享,转载请先联系原作者,谢谢!

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-01-10,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 安徽开发者圈 微信公众号,前往查看

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

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

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