跳转至

Spring 资源教程

原文: http://zetcode.com/spring/resource/

Spring Resource教程展示了如何使用Resource在 Spring 应用中使用各种资源。

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

Spring 资源

Resource从基础资源的实际类型中抽象出来,例如文件或类路径资源。 它可以用来标识本地或远程资源。

Spring ApplicationContext包含getResource()方法,该方法返回指定资源类型的资源句柄。 它可以是类路径,文件或 URL 资源。

Spring 资源示例

该应用使用 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>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/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;

使用@Autowired将服务 bean 注入到类中。

myService.readWebPage();
myService.readFile();

我们称为myService方法。

在本教程中,我们展示了如何使用Resource来读取本地文本文件和网页。

您可能也对这些相关教程感兴趣: Spring @Qualifier注解教程Spring 单例范围 beanSpring C-命名空间教程Spring BeanDefinitionBuilder教程Spring bean 引用教程Java 教程


我们一直在努力

apachecn/AiLearning

【布客】中文翻译组