<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # 在 Spring Boot 中加載資源 > 原文: [http://zetcode.com/springboot/loadresource/](http://zetcode.com/springboot/loadresource/) 在本教程中,我們將展示如何在 Spring Boot 應用中加載資源。 Spring 是用于創建企業應用的流行 Java 應用框架。 Spring Boot 是一種以最少的精力創建獨立的,基于生產級別的基于 Spring 的應用的方法。 ## Spring Boot 資源 資源是程序需要以與程序代碼的位置無關的方式訪問的數據,例如圖像,音頻和文本。 由于`java.net.URL`不足以處理各種低級資源,因此 Spring 引入了`org.springframework.core.io.Resource`。 要訪問資源,我們可以使用`@Value`注解或`ResourceLoader`類。 ## Spring Boot 加載資源示例 我們的應用是一個 Spring Boot 命令行應用,它可以計算文本文件中單詞的出現次數。 該文件位于`src/main/resources`目錄中,這是應用資源的標準 Maven 位置。 ```java pom.xml src ├───main │ ├───java │ │ └───com │ │ └───zetcode │ │ │ Application.java │ │ │ MyRunner.java │ │ └───service │ │ CountWords.java │ └───resources │ application.yaml │ thermopylae.txt └───test └───java ``` 這是項目結構。 `pom.xml` ```java <?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>springbootresource</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.5.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> ``` 這是 Maven 構建文件。 Spring Boot 啟動器是一組方便的依賴項描述符,我們可以在我們的應用中包含這些描述符。 它們極大地簡化了 Maven 配置。 `spring-boot-starter-parent`提供了 Spring Boot 應用的一些常見配置。 `spring-boot-starter`依賴項是一個核心啟動器,其中包括自動配置支持,日志記錄和 YAML。 `spring-boot-maven-plugin`在 Maven 中提供了 Spring Boot 支持,使我們可以打包可執行的 JAR 或 WAR 檔案。 它的`spring-boot:run`目標運行 Spring Boot 應用。 `resources/application.yml` ```java spring: main: banner-mode: "off" logging: level: org: springframework: ERROR com: zetcode: INFO ``` `application.yml`文件包含 Spring Boot 應用的各種配置設置。 我們具有`banner-mode`屬性,可在其中關閉 Spring 橫幅。 另外,我們將 spring 框架的日志記錄級別設置為`ERROR`,將我們的應用設置為 INFO。 該文件位于`src/main/resources`目錄中。 `resources/thermopylae.txt` ```java The Battle of Thermopylae was fought between an alliance of Greek city-states, led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the course of three days, during the second Persian invasion of Greece. It took place simultaneously with the naval battle at Artemisium, in August or September 480 BC, at the narrow coastal pass of Thermopylae. The Persian invasion was a delayed response to the defeat of the first Persian invasion of Greece, which had been ended by the Athenian victory at the Battle of Marathon in 490 BC. Xerxes had amassed a huge army and navy, and set out to conquer all of Greece. ``` 這是我們在應用中讀取的文本文件。 它也位于`src/main/resources`目錄中。 `com/zetcode/service/CountWords.java` ```java package com.zetcode.service; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; @Component public class CountWords { public Map<String, Integer> getWordsCount(Resource res) throws IOException { Map<String, Integer> wordCount = new HashMap<>(); List<String> lines = Files.readAllLines(Paths.get(res.getURI()), StandardCharsets.UTF_8); for (String line : lines) { String[] words = line.split("\\s+"); for (String word : words) { if (word.endsWith(".") || word.endsWith(",")) { word = word.substring(0, word.length() - 1); } if (wordCount.containsKey(word)) { wordCount.put(word, wordCount.get(word) + 1); } else { wordCount.put(word, 1); } } } return wordCount; } } ``` `CountWords`是一個 Spring 托管的 bean,它執行給定文件中的單詞計數。 文本從文件中讀取到句子列表中。 句子被分成單詞并計數。 ```java Map<String, Integer> wordCount = new HashMap<>(); ``` `wordCount`是一個映射,其中鍵是單詞,頻率是整數。 ```java List<String> lines = Files.readAllLines(Paths.get(res.getURI()), StandardCharsets.UTF_8); ``` 我們使用`Files.readAllLines()`方法一次讀取所有內容。 `Files.readAllLines()`方法返回字符串列表。 ```java for (String line : lines) { String[] words = line.split(" "); ... ``` 我們遍歷這些線,將它們分成單詞; 單詞之間用空格隔開。 ```java if (word.endsWith(".") || word.endsWith(",")) { word = word.substring(0, word.length()-1); } ``` 我們刪除尾隨點和逗號。 ```java if (wordCount.containsKey(word)) { wordCount.put(word, wordCount.get(word) + 1); } else { wordCount.put(word, 1); } ``` 如果單詞已經在映射中,則增加其頻率; 否則,我們將其插入映射并將其頻率設置為 1。 `com/zetcode/MyRunner.java` ```java package com.zetcode; import com.zetcode.count.CountWords; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.core.io.Resource; import org.springframework.stereotype.Component; @Component public class MyRunner implements CommandLineRunner { @Value("classpath:thermopylae.txt") private Resource res; @Autowired private CountWords countWords; @Override public void run(String... args) throws Exception { Map<String, Integer> words = countWords.getWordsCount(res); for (String key : words.keySet()) { System.out.println(key + ": " + words.get(key)); } } } ``` 使用`CommandLineRunner`,Spring Boot 應用在終端上運行。 ```java @Value("classpath:thermopylae.txt") private Resource res; ``` 使用`@Value`注解,將文件設置為資源。 ```java @Autowired private CountWords countWords; ``` 我們注入了`CountWords` bean。 ```java Map<String, Integer> words = countWords.getWordsCount(res); for (String key : words.keySet()) { System.out.println(key + ": " + words.get(key)); } ``` 我們調用`getWordsCount()`方法,并接收單詞及其頻率的映射。 我們遍歷映射,并將鍵/值對打印到控制臺。 `com/zetcode/Application.java` ```java package com.zetcode; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` `Application`設置 Spring Boot 應用。 `@SpringBootApplication`啟用自動配置和組件掃描。 ## 使用`ResourceLoader` 以前,我們使用`@Value`注解來加載資源。 以下是`ResourceLoader`的替代解決方案。 `com/zetcode/MyRunner.java` ```java package com.zetcode; import com.zetcode.count.CountWords; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; @Component public class MyRunner implements CommandLineRunner { @Autowired private ResourceLoader resourceLoader; @Autowired private CountWords countWords; @Override public void run(String... args) throws Exception { Resource res = resourceLoader.getResource("classpath:thermopylae.txt"); Map<String, Integer> words = countWords.getWordsCount(res); for (String key : words.keySet()) { System.out.println(key + ": " + words.get(key)); } } } ``` 或者,我們可以使用`ResourceLoader`加載資源。 ```java @Autowired private ResourceLoader resourceLoader; ``` `ResourceLoader`被注入到現場。 ```java Resource res = resourceLoader.getResource("classpath:thermopylae.txt"); ``` `Resource`是通過`getResource()`方法從資源加載器獲得的。 ## 運行應用 該應用在命令行上運行。 ```java $ mvn spring-boot:run -q ... been: 1 Athenian: 1 alliance: 1 navy: 1 fought: 1 led: 1 delayed: 1 had: 2 during: 1 three: 1 second: 1 Greece: 3 ... ``` 使用`mvn spring-boot:run`命令,運行應用。 `-q`選項禁止 Maven 日志。 在本教程中,我們使用了 Spring Boot 應用中的資源。 我們使用`@Value`和`ResourceLoader`加載資源文件。 列出[所有 Spring Boot 教程](/all/#springboot)。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看