Spring ClassPathResource

Spring ClassPathResource 教程显示了如何在 Spring 应用中使用 ClassPathResource 读取资源。

Spring 是用于创建企业应用的流行 Java 应用框架。

Spring ClassPathResource

ClassPathResource允许从 Java 类路径获取资源。

Spring ClassPathResource示例

该应用从 Java 类路径中的文件读取文本数据。

src
├───main
│   ├───java
│   │   └───com
│   │       └───zetcode
│   │           │   Application.java
│   │           └───service
│   │                   ReadWordsService.java
│   └───resources
│           logback.xml
│           my-beans.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>classpathres</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <spring-version>5.1.3.RELEASE</spring-version>

    </properties>

    <dependencies>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</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>1.6.0</version>
                <configuration>
                    <mainClass>com.zetcode.Application</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

pom.xml文件中,我们具有基本的 Spring 依赖项spring-corespring-context和日志记录logback-classic依赖项。

exec-maven-plugin用于在命令行上从 Maven 执行 Spring 应用。

resources/my-beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="readWordsService" class="com.zetcode.service.ReadWordsService"/>

</beans>

my-beans.xml文件中,我们配置readWordsService bean。 它成为 Spring 托管的 bean。

resources/words.txt

sky
blue
mountain
fresh
cloud
rock
water
melon

resources目录包含在类路径中。 该应用从words.txt文件中读取单词。

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} [%thread] %blue(%-5level) %magenta(%logger{36}) - %msg %n
            </Pattern>
        </encoder>
    </appender>

    <root>
        <level value="INFO" />
        <appender-ref ref="consoleAppender" />
    </root>
</configuration>

logback.xml是 Logback 日志库的配置文件。

com/zetcode/service/ReadWordsService.java

package com.zetcode.service;

import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

public class ReadWordsService {

    public List<String> readWords() throws IOException {

        var res = new ClassPathResource("words.txt");

        var myFile = res.getFile();
        var lines = Files.readAllLines(myFile.toPath());

        return lines;
    }
}

ReadWordsService将单词读入列表,并将列表返回给客户端。

var res = new ClassPathResource("words.txt");

ClassPathResource用于定位文本文件。

com/zetcode/Application.java

package com.zetcode;

import com.zetcode.service.ReadWordsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.GenericXmlApplicationContext;
import java.io.IOException;

public class Application {

    private static final Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) throws IOException {

        var ctx = new GenericXmlApplicationContext("my-beans.xml");

        var wordsService = (ReadWordsService) ctx.getBean("readWordsService");
        var words = wordsService.readWords();

        words.forEach(word -> logger.info(word));

        ctx.close();
    }
}

这是主要的应用类。

var wordsService = (ReadWordsService) ctx.getBean("readWordsService");
var words = wordsService.readWords();

words.forEach(word -> logger.info(word));

我们从容器中检索readWordsService bean,并调用其readWords()方法。 文字将打印到控制台。

$ mvn -q exec:java
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - sky
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - blue
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - mountain
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - fresh
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - cloud
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - rock
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - water
00:25:49.008 [com.zetcode.Application.main()] INFO  com.zetcode.Application - melon

我们运行该应用。

在本教程中,我们使用了 Spring 的ClassPathResource

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程