Spring Resource 教程
最后修改于 2023 年 10 月 18 日
Spring Resource 教程演示了如何在 Spring 应用程序中使用 Resource 来处理各种资源。
Spring 是一个流行的 Java 应用程序框架,用于创建企业级应用程序。
Spring Resource
Resource 抽象了底层资源的实际类型,例如文件或类路径资源。它可以用于标识本地或远程资源。
Spring 的 ApplicationContext 包含 getResource 方法,该方法返回指定资源类型的资源句柄。它可以是类路径、文件或 URL 资源。
Spring Resource 示例
该应用程序使用 Spring 的 Resource 来读取本地文件和远程网页。
pom.xml
src
├───main
│ ├───java
│ │ └───com
│ │ └───zetcode
│ │ │ Application.java
│ │ └───service
│ │ MyService.java
│ └───resources
│ logback.xml
│ words.txt
└───test
└───java
这是项目结构。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>resourceex</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<spring-version>5.3.23</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring-version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<mainClass>com.zetcode.Application</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
在 pom.xml 文件中,我们有基本的 Spring 依赖 spring-core、spring-context 和日志 logback-classic 依赖。
exec-maven-plugin 用于从 Maven 命令行执行 Spring 应用程序。
resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<logger name="org.springframework" level="ERROR"/>
<logger name="com.zetcode" level="INFO"/>
<appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
</Pattern>
</encoder>
</appender>
<root>
<level value="INFO" />
<appender-ref ref="consoleAppender" />
</root>
</configuration>
logback.xml 是 Logback 日志库的配置文件。
resources/words.txt
clean sky forest blue crystal cloud river
words.txt 文件包含几个单词。
com/zetcode/MyService.java
package com.zetcode.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@Service
public class MyService {
private static final Logger logger = LoggerFactory.getLogger(MyService.class);
@Autowired
private ApplicationContext ctx;
public void readWebPage() {
var res = ctx.getResource("http://webcode.me");
try (var is = new InputStreamReader(res.getInputStream());
var bis = new BufferedReader(is)) {
bis.lines().forEach(System.out::println);
} catch (IOException ex) {
logger.warn("{}", ex);
}
}
public void readFile() {
// var res = ctx.getResource("file:C:/Users/Jano/Documents/words.txt");
var res = ctx.getResource("classpath:words.txt");
try (var is = new InputStreamReader(res.getInputStream());
var bis = new BufferedReader(is)) {
bis.lines().forEach(System.out::println);
} catch (IOException ex) {
logger.warn("{}", ex);
}
}
}
MyService 包含两个方法,用于读取网页和本地文本文件。
@Autowired private ApplicationContext ctx;
我们注入了 ApplicationContext。我们使用它的 getResource 方法来获取资源处理器。
var res = ctx.getResource("http://webcode.me");
我们从网页获取一个 Resource。
// var res = ctx.getResource("file:C:/Users/Jano/Documents/words.txt");
var res = ctx.getResource("classpath:words.txt");
我们可以从绝对文件路径或类路径获取 Resource。
com/zetcode/Application.java
package com.zetcode;
import com.zetcode.service.MyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = "com.zetcode")
public class Application {
private static final Logger logger = LoggerFactory.getLogger(Application.class);
@Autowired
private MyService myService;
public static void main(String[] args) {
var ctx = new AnnotationConfigApplicationContext(Application.class);
var app = ctx.getBean(Application.class);
app.run();
ctx.close();
}
public void run() {
myService.readWebPage();
myService.readFile();
}
}
这是主应用程序类。
@Autowired private MyService myService;
一个服务 bean 通过 @Autowired 注入到该类中。
myService.readWebPage(); myService.readFile();
我们调用 myService 方法。
在本文中,我们展示了如何使用 Resource 来读取本地文本文件和网页。
作者
列出 所有 Spring 教程。