springboot加载资源
时间: 2023-07-02 19:18:17 浏览: 48
Spring Boot 在加载资源时会按照以下规则搜索资源:
1. classpath:/META-INF/resources/
2. classpath:/resources/
3. classpath:/static/
4. classpath:/public/
其中,classpath 表示项目的 classpath 路径,即 src/main/resources 目录。
例如,如果我们在 src/main/resources 下创建了一个名为 test.txt 的文件,则可以通过以下方式访问它:
```
InputStream is = getClass().getResourceAsStream("/test.txt");
```
其中,"/" 表示项目的 classpath 路径。如果文件路径为 "/static/test.txt",则可以通过以下方式访问:
```
InputStream is = getClass().getResourceAsStream("/static/test.txt");
```
同时,Spring Boot 还支持自定义资源的加载路径,只需要在 application.properties 或 application.yml 中配置:
```
spring.resources.static-locations=classpath:/my-resources/
```
这将会在 classpath:/my-resources/ 目录下查找静态资源。
相关问题
springboot 加载资源文件
Spring Boot可以使用多种方式加载资源文件。其中一种方式是使用Spring的ResourceLoader接口来加载资源文件。通过ResourceLoader的getResource()方法,可以传入资源文件路径参数,返回一个Resource对象。然后可以通过Resource对象获取资源文件的输入流,如下所示:\[1\]
```java
@Autowired
private ResourceLoader resourceLoader;
public void readResourceFile() throws IOException {
Resource resource = resourceLoader.getResource("classpath:file.txt");
InputStream inputStream = resource.getInputStream();
}
```
另一种方式是使用FileSystemResource类加载资源文件。这种方式适用于在使用Spring Boot插件打成jar包后,启动路径与IDEA中的路径发生变化的情况。通过FileSystemResource类可以直接指定资源文件的路径,如下所示:\[2\]
```java
Resource resource = new FileSystemResource("path/to/file.txt");
InputStream inputStream = resource.getInputStream();
```
还可以使用ResourceUtils类来加载文件。ResourceUtils提供了一些静态方法,可以根据不同的前缀(如"classpath:"、"file:"等)来加载资源文件,如下所示:\[3\]
```java
Resource resource = ResourceUtils.getURL("classpath:file.txt");
InputStream inputStream = resource.getInputStream();
```
以上是Spring Boot加载资源文件的几种常用方式。根据具体的需求和场景,选择合适的方式来加载资源文件即可。
#### 引用[.reference_title]
- *1* *3* [springboot项目读取 resources 目录下的文件的9种方式(总结)](https://blog.csdn.net/weixin_43025151/article/details/129819888)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [SpringBoot:加载和读取jar包外面的资源文件](https://blog.csdn.net/weixin_45492007/article/details/122519728)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
springboot加载机制
SpringBoot的加载机制是通过加载不同的属性资源加载器来实现的。在底层构建加载的Loader类的时候,SpringBoot从spring.factories的配置文件中读取到了两种属性资源加载器并进行了实例化,即PropertiesPropertySourceLoader和YamlPropertySourceLoader。当启动SpringBoot应用时,默认会加载名为application的配置文件。如果想要指定特定名称的配置文件,可以在启动之前配置spring.config.name属性。