在Spring Boot中从类路径加载文件
介绍
创建Spring Boot Web应用程序时,有时有时需要从类路径中加载文件;war和jar的加载文件格式是不一样的
在下面,您将找到在WAR和JAR中加载文件的解决方案。
资源加载器
使用Java,您可以使用当前线程的classLoader并尝试加载文件,但是Spring Framework为您提供了更为优雅的解决方案,例如ResourceLoader。
您只需要自动连接ResourceLoader
,然后调用getResource(„somePath“)
方法即可。
在Spring Boot(WAR)中从资源目录/类路径加载文件的示例
在以下示例中,我们从类路径中加载名为GeoLite2-Country.mmdb的文件作为资源,然后将其作为File
对象检索。
@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.");
}
}
}
}
在Spring Boot(JAR)中从资源目录/类路径加载文件的示例
如果您想从Spring Boot JAR中的 classpath加载文件,则必须使用该resource.getInputStream()
方法将其作为InputStream检索。如果尝试使用resource.getFile()
该方法,则会收到错误消息,因为Spring尝试访问文件系统路径,但无法访问JAR中的路径。
@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.");
}
}
}
}
在Spring Boot中从类路径加载文件的更多相关文章
- Spring Boot 2.4 配置文件将加载机制大变化
Spring Boot 2.4.0.M2 刚刚发布,它对 application.properties 和 application.yml 文件的加载方式进行重构.如果应用程序仅使用单个 applic ...
- Spring Boot中普通类获取Spring容器中的Bean
我们知道如果我们要在一个类使用spring提供的bean对象,我们需要把这个类注入到spring容器中,交给spring容器进行管理,但是在实际当中,我们往往会碰到在一个普通的Java类中,自己动手n ...
- 精尽Spring Boot源码分析 - 配置加载
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- JVM中java类的加载时机(转载:http://blog.csdn.net/chenleixing/article/details/47099725)
Java虚拟机把描述类的数据从Class文件加载到内存,并对数据进行校验.转换解析和初始化,最终形成可以被虚拟机直接使用的Java类型,这就是虚拟机的加载机制.类从被加载到虚拟机内存中开始,到卸载出内 ...
- Spring Boot 启动以后然后再加载缓存数据 CommandLineRunner
实际应用中,我们会有在项目服务启动完成以后去加载一些数据或做一些事情(比如缓存)这样的需求. 为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRu ...
- Spring Boot源码分析-配置文件加载原理
在Spring Boot源码分析-启动过程中我们进行了启动源码的分析,大致了解了整个Spring Boot的启动过程,具体细节这里不再赘述,感兴趣的同学可以自行阅读.今天让我们继续阅读源码,了解配置文 ...
- 解决spring boot中普通类中使用service为null 的方法
我使用的是springboot+mybatisplus +mysql1.创建一个SpringUtil工具类 import org.springframework.beans.BeansExceptio ...
- Spring Boot中application.properties和application.yml文件
application.properties和application.yml文件可以放在一下四个位置: 外置,在相对于应用程序运行目录的/congfig子目录里. 外置,在应用程序运行的目录里 内置, ...
- (转)spring boot实战(第六篇)加载application资源文件源码分析
原文:http://blog.csdn.net/liaokailin/article/details/48878447
随机推荐
- Auto-Encoding Variational Bayes
目录 主要内容 Encoder (损失part1) Decoder (损失part2) 伯努利分布 高斯分布 代码 Kingma D P, Welling M. Auto-Encoding Varia ...
- ImageNet2017文件下载
ImageNet2017文件下载 文件说明 imagenet_object_localization.tar.gz包含训练集和验证集的图像数据和地面实况,以及测试集的图像数据. 图像注释以PASCAL ...
- Java程序设计基础笔记 • 【第5章 循环结构】
全部章节 >>>> 本章目录 5.1 while循环结构 5.1.1 循环简介 5.1.2 while循环 5.1.3 while循环的使用 5.1.4 while循环的注 ...
- Roslyn+T4+EnvDTE项目完全自动化(3) ——生成c++代码
C++语法复杂,写一个示例通过T4可生成c++代码 需求:数据库,生成c++增,删,改,查代码 数据生成c++类,包含所有字段 自动识别数据的主键Key 查询生成赋值类字段,类型转换 通过类自动生成s ...
- SpringCloud创建Gateway模块
1.说明 本文详细介绍Spring Cloud创建Gateway模块的方法, 基于已经创建好的Spring Cloud父工程, 请参考SpringCloud创建项目父工程, 和已经创建好的Eureka ...
- [Azure DevOps] 管理测试计划、测试套件和测试用例
我喜欢测试计划,它能让团队清楚测试进度,还能妥善分配测试人员,更重要的是它能保证测试质量和效率.Azure DevOps 里提供了 Test Plans 这个模块用于管理测试计划. 1. Azure ...
- Lomsat gelral
题目描述 You are given a rooted tree with root in vertex 11 . Each vertex is coloured in some colour. Le ...
- python3 f-string格式化字符串的高级用法
从Python 3.6开始,f-string是格式化字符串的一种很好的新方法.与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快! 在Python 3.6之前,有两种将Python表 ...
- Python之路 - Day4 - Python基础4 (新版)
本节内容 迭代器&生成器 装饰器 Json & pickle 数据序列化 软件目录结构规范 作业:ATM项目开发 1.列表生成式,迭代器&生成器 列表生成式 孩子,我现在有个需 ...
- PingFang(苹方)字体的引用
原文 链接:https://pan.baidu.com/s/1rw39Yqo9fv9BYz_JZ5lyRw 提取码:o7kf 苹方-简 常规体 font-family: pingFangSC-Regu ...