在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
随机推荐
- Towards Evaluating the Robustness of Neural Networks
目录 概 主要内容 基本的概念 目标函数 如何选择c 如何应对Box约束 attack attack attack Nicholas Carlini, David Wagner, Towards Ev ...
- Windows环境下使用Linux命令
1.说明 如何在Windows环境下使用Linux命令, 这是一个屡见不鲜的问题, 而且已经有很多解决方法, 下面仅推荐几个我觉得好用的工具, 这些工具可能就是我们常用的软件, 而且已经在Window ...
- MongoDB分片集群搭建及扩容
### 实验:分片集群搭建及扩容#### 实验目标及流程 * 目标:学习如何搭建一个两分片的分片集群 * 环境:3台Linux虚拟机器,4Core 8GB * 步骤: * 配置域名解析 * 准备分片目 ...
- Drupal 8 环境搭建部署
运行环境安装 系统:Ubuntu Server 16.04 (ubuntu-16.04.4-server-amd64.iso) Web服务器:Apache / 2.4.18 数据库:Mysql / ...
- 初识python:tkinter 实现 弹球小游戏(面向对象)
使用蹩脚式面相对象,实现弹球小游戏(非面向对象实现,主要介绍tk基础用法). #!/user/bin env python # author:Simple-Sir # time:2020/8/7 10 ...
- 关于Mysql的Qcache优化
query_cache_size = 64M 指定MySQL查询缓冲区的大小.可以通过在MySQL控制台执行以下命令观察:# > SHOW VARIABLES LIKE '%query_cach ...
- js 调用同级的 iframe 方法
有两个 iframe <iframe id="a"> <script> function food(a){ return a+1; } </scrip ...
- WAFW00F waf识别工具 源码学习
我实习工作的第一个任务根据已有的java waf识别工具 实现了一个python的waf识别工具 代码结构非常乱 仅仅达到了能用的水平. 顶头svp推荐这个项目当时我已经写好了开始用了自己的 稍微看了 ...
- WEB开发的相关知识(Tomcat)
Internet上供外界访问的Web资源分为 静态web资源(如html 页面):指web页面中供人们浏览的数据始终是不变. 动态web资源:指web页面中供人们浏览的数据是由程序产生的,不同时间点访 ...
- go语言 strconv.ParseInt 的实现分析
字符串与数值之间进行转换是一个高频操作,在go语言中,SDK提供 strconv.ParseInt 将字符串转换为数值,strconv.FormatInt 可以将数值转换为字符串. 1.首先看下 st ...