提交 f7378e26 编写于 作者: Miykael_xxm's avatar Miykael_xxm 🚴

机翻内容

上级 0c6ae7d1
......@@ -123,6 +123,7 @@ module.exports = {
collapsable: false,
children: [
"/en/why-spring.md",
"/en/introducing-spring-boot.md",
"/en/quickstart.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
......@@ -133,7 +134,8 @@ module.exports = {
collapsable: false,
children: [
"/en/system-requirements.md",
"/en/installing.md"
"/en/installing.md",
"/en/initializr.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
},
......@@ -142,7 +144,8 @@ module.exports = {
sidebarDepth: 2,
collapsable: false,
children: [
"/en/vscode_ide.md"
"/en/vscode_java.md",
"/en/intellij_idea.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
},
......@@ -151,7 +154,9 @@ module.exports = {
sidebarDepth: 2,
collapsable: false,
children: [
"/en/initializr.md"
"/en/getting-started_first-application.md",
"/en/rest-service.md",
"/en/consuming-rest.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
}
......@@ -183,6 +188,7 @@ module.exports = {
collapsable: false,
children: [
"why-spring.md",
"introducing-spring-boot.md",
"quickstart.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
......@@ -193,7 +199,8 @@ module.exports = {
collapsable: false,
children: [
"system-requirements.md",
"installing.md"
"installing.md",
"initializr.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
},
......@@ -202,7 +209,8 @@ module.exports = {
sidebarDepth: 2,
collapsable: false,
children: [
"vscode_ide.md"
"vscode_java.md",
"intellij_idea.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
},
......@@ -211,7 +219,9 @@ module.exports = {
sidebarDepth: 2,
collapsable: false,
children: [
"initializr.md"
"getting-started_first-application.md",
"rest-service.md",
"consuming-rest.md"
],
initialOpenGroupIndex: 0 // 可选的, 默认值是 0
}
......
# 使用 RESTful Web 服务
本指南将引导您完成创建使用 RESTful Web 服务的应用程序的过程。
## 你将建造什么
您将构建一个应用程序,该应用程序使用 Spring`RestTemplate`在https://quoters.apps.pcfone.io/api/random检索随机 Spring Boot 报价。
## 你需要什么
- 约15分钟
- 最喜欢的文本编辑器或 IDE
- [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html)或更高版本
- [Gradle 4+](http://www.gradle.org/downloads)[Maven 3.2+](https://maven.apache.org/download.cgi)
- 您还可以将代码直接导入 IDE:
- [弹簧工具套件 (STS)](https://spring.io/guides/gs/sts)
- [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## 如何完成本指南
像大多数 Spring[入门指南](https://spring.io/guides)一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到工作代码。
**从头开始**,请继续[从 Spring Initializr 开始](https://spring.io/guides/gs/consuming-rest/#scratch)
**跳过基础知识**,请执行以下操作:
- [下载](https://github.com/spring-guides/gs-consuming-rest/archive/main.zip)并解压缩本指南的源存储库,或使用[Git](https://spring.io/understanding/Git)克隆它:`git clone https://github.com/spring-guides/gs-consuming-rest.git`
- 光盘进入`gs-consuming-rest/initial`
- 跳转到[获取 REST 资源](https://spring.io/guides/gs/consuming-rest/#initial)
**完成后**,您可以对照中的代码检查结果`gs-consuming-rest/complete`
## 从 Spring Initializr 开始
您可以使用这个[预先初始化的项目](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.5.5&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=consuming-rest&name=consuming-rest&description=Demo project for Spring Boot&packageName=com.example.consuming-rest&dependencies=web)并单击 Generate 下载 ZIP 文件。此项目配置为适合本教程中的示例。
手动初始化项目:
1. 导航到[https://start.spring.io](https://start.spring.io/)。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。
2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
3. 单击**Dependencies**并选择**Spring Web**
4. 单击**生成**
5. 下载生成的 ZIP 文件,该文件是根据您的选择配置的 Web 应用程序的存档。
如果您的 IDE 具有 Spring Initializr 集成,您可以从您的 IDE 完成此过程。
你也可以从 Github 上 fork 项目并在你的 IDE 或其他编辑器中打开它。
## 获取 REST 资源
完成项目设置后,您可以创建一个使用 RESTful 服务的简单应用程序。
一个 RESTful 服务已经在https://quoters.apps.pcfone.io/api/random建立起来。它随机获取有关 Spring Boot 的引用并将它们作为 JSON 文档返回。
如果您通过 Web 浏览器或 curl 请求该 URL,您会收到如下所示的 JSON 文档:
```
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}
```
这很容易,但在通过浏览器或 curl 获取时并不是非常有用。
以编程方式使用 REST Web 服务的更有用的方法。为了帮助您完成这项任务,Spring 提供了一个方便的模板类,称为[`RestTemplate`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html). `RestTemplate`使与大多数 RESTful 服务的交互成为单行咒语。它甚至可以将该数据绑定到自定义域类型。
首先,您需要创建一个域类来包含您需要的数据。以下清单显示了`Quote`可以用作域类的类:
```
src/main/java/com/example/consumingrest/Quote.java
```
```
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
```
这个简单的 Java 类有一些属性和匹配的 getter 方法。它使用`@JsonIgnoreProperties`来自 Jackson JSON 处理库的注释来指示任何未绑定在此类型中的属性应被忽略。
要将您的数据直接绑定到您的自定义类型,您需要将变量名称指定为与从 API 返回的 JSON 文档中的键完全相同。如果您的 JSON 文档中的变量名称和键不匹配,您可以使用`@JsonProperty`注释来指定 JSON 文档的确切键。(此示例将每个变量名称与 JSON 键匹配,因此此处不需要该注释。)
您还需要一个额外的类来嵌入内部引用本身。该类`Value`满足了这一需求,并显示在以下清单 (at `src/main/java/com/example/consumingrest/Value.java`) 中:
```
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
private Long id;
private String quote;
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
}
```
这使用相同的注释,但映射到其他数据字段。
## 完成申请
Initalizr 创建一个带有`main()`方法的类。以下清单显示了 Initializr 创建的类(at `src/main/java/com/example/consumingrest/ConsumingRestApplication.java`):
```
package com.example.consumingrest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumingRestApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
}
```
现在您需要向`ConsumingRestApplication`该类添加一些其他内容,以使其显示来自我们 RESTful 源的引用。您需要添加:
- 一个记录器,用于将输出发送到日志(在此示例中为控制台)。
- A `RestTemplate`,它使用 Jackson JSON 处理库来处理传入的数据。
- A在启动`CommandLineRunner`时运行`RestTemplate`(并因此获取我们的报价)。
以下清单显示了完成的`ConsumingRestApplication`类 (at `src/main/java/com/example/consumingrest/ConsumingRestApplication.java`):
```
package com.example.consumingrest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumingRestApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"https://quoters.apps.pcfone.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}
```
## 运行应用程序
您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的单个可执行 JAR 文件并运行它。构建可执行 jar 可以在整个开发生命周期、跨不同环境等中轻松地作为应用程序交付、版本化和部署服务。
如果您使用 Gradle,则可以使用`./gradlew bootRun`. 或者,您可以使用构建 JAR 文件`./gradlew build`,然后运行 JAR 文件,如下所示:
```
java -jar build/libs/gs-consuming-rest-0.1.0.jar
```
如果您使用 Maven,则可以使用`./mvnw spring-boot:run`. 或者,您可以使用构建 JAR 文件,`./mvnw clean package`然后运行该 JAR 文件,如下所示:
```
java -jar target/gs-consuming-rest-0.1.0.jar
```
此处描述的步骤创建了一个可运行的 JAR。您还可以[构建经典的 WAR 文件](https://spring.io/guides/gs/convert-jar-to-war/)
您应该看到类似于以下的输出,但带有随机引用:
```
2019-08-22 14:06:46.506 INFO 42940 --- [ main] c.e.c.ConsumingRestApplication : Quote{type='success', value=Value{id=1, quote='Working with Spring Boot is like pair-programming with the Spring developers.'}}
```
如果您看到显示为 的错误,`Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote]`则可能是您处于无法连接到后端服务的环境中(如果您可以访问它,它将发送 JSON)。也许您是公司代理的幕后黑手。尝试将`http.proxyHost``http.proxyPort`系统属性设置为适合您的环境的值。
## 概括
恭喜!您刚刚使用 Spring Boot 开发了一个简单的 REST 客户端。
原文链接: https://spring.io/guides/gs/consuming-rest/
# Spring 中文文档社区
从实操的角度整理翻译`Spring`相关文档,包括`快速开始``安装指南``开发工具配置``代码案例`等。
## 内容大纲
- 概述
- 快速开始
- 系统要求
- 安装指南
- 脚手架
- VSCode
- IntelliJ IDEA
- 开发你的第一个 Spring Boot 应用程序
- 构建 RESTful Web 服务
- 使用 RESTful Web 服务
## 参与贡献
所有 **`Java Spring 熟练使用者`** 可以参与到`Spring 中文文档社区`的建设中来,选择自己感兴趣题目,可以直接撰写文章,也可以翻译 [Spring 官方](https://spring.io/) 上面的内容,也可以校对别人翻译的文章。具体贡献流程如下。
![](https://gitcode.net/zkxw2008/my-material/-/raw/master/spring/readme-1.png)
1、Fork[此仓库](https://gitcode.net/dev-cloud/spring)到自己的[GitCode](https://gitcode.net/)账户下。
2、查看[Issue](https://gitcode.net/dev-cloud/spring/-/issues) 确定自己需要完成的题目。
3、对于已有中文的文档内容文件,可以执行校对。
4、对于暂时无中文文档内容的,可以直接贡献(翻译/撰写)原创中文文档。
5、内容完成者向[此仓库](https://gitcode.net/dev-cloud/spring)提交 PR(Pull Request)。
6、[此仓库](https://gitcode.net/dev-cloud/spring)审核人员审核通过,符合要求的,即会 Merge 到[此仓库](https://gitcode.net/dev-cloud/spring)中。
7、被 Merged 的 PR,会得到 200 ~ 500元不等的奖励。
# Consuming a RESTful Web Service
This guide walks you through the process of creating an application that consumes a RESTful web service.
## What You Will Build
You will build an application that uses Spring’s `RestTemplate` to retrieve a random Spring Boot quotation at https://quoters.apps.pcfone.io/api/random.
## What You Need
- About 15 minutes
- A favorite text editor or IDE
- [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) or later
- [Gradle 4+](http://www.gradle.org/downloads) or [Maven 3.2+](https://maven.apache.org/download.cgi)
- You can also import the code straight into your IDE:
- [Spring Tool Suite (STS)](https://spring.io/guides/gs/sts)
- [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## How to complete this guide
Like most Spring [Getting Started guides](https://spring.io/guides), you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
To **start from scratch**, move on to [Starting with Spring Initializr](https://spring.io/guides/gs/consuming-rest/#scratch).
To **skip the basics**, do the following:
- [Download](https://github.com/spring-guides/gs-consuming-rest/archive/main.zip) and unzip the source repository for this guide, or clone it using [Git](https://spring.io/understanding/Git): `git clone https://github.com/spring-guides/gs-consuming-rest.git`
- cd into `gs-consuming-rest/initial`
- Jump ahead to [Fetching a REST Resource](https://spring.io/guides/gs/consuming-rest/#initial).
**When you finish**, you can check your results against the code in `gs-consuming-rest/complete`.
## Starting with Spring Initializr
You can use this [pre-initialized project](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.5.5&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=consuming-rest&name=consuming-rest&description=Demo project for Spring Boot&packageName=com.example.consuming-rest&dependencies=web) and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
To manually initialize the project:
1. Navigate to [https://start.spring.io](https://start.spring.io/). This service pulls in all the dependencies you need for an application and does most of the setup for you.
2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
3. Click **Dependencies** and select **Spring Web**.
4. Click **Generate**.
5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
You can also fork the project from Github and open it in your IDE or other editor.
## Fetching a REST Resource
With project setup complete, you can create a simple application that consumes a RESTful service.
A RESTful service has been stood up at https://quoters.apps.pcfone.io/api/random. It randomly fetches quotations about Spring Boot and returns them as JSON documents.
If you request that URL through a web browser or curl, you receive a JSON document that looks something like this:
```
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}
```
That is easy enough but not terribly useful when fetched through a browser or through curl.
A more useful way to consume a REST web service is programmatically. To help you with that task, Spring provides a convenient template class called [`RestTemplate`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html). `RestTemplate` makes interacting with most RESTful services a one-line incantation. And it can even bind that data to custom domain types.
First, you need to create a domain class to contain the data that you need. The following listing shows the `Quote` class, which you can use as your domain class:
```
src/main/java/com/example/consumingrest/Quote.java
```
```
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
@Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
```
This simple Java class has a handful of properties and matching getter methods. It is annotated with `@JsonIgnoreProperties` from the Jackson JSON processing library to indicate that any properties not bound in this type should be ignored.
To directly bind your data to your custom types, you need to specify the variable name to be exactly the same as the key in the JSON document returned from the API. In case your variable name and key in JSON doc do not match, you can use `@JsonProperty` annotation to specify the exact key of the JSON document. (This example matches each variable name to a JSON key, so you do not need that annotation here.)
You also need an additional class, to embed the inner quotation itself. The `Value` class fills that need and is shown in the following listing (at `src/main/java/com/example/consumingrest/Value.java`):
```
package com.example.consumingrest;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Value {
private Long id;
private String quote;
public Value() {
}
public Long getId() {
return this.id;
}
public String getQuote() {
return this.quote;
}
public void setId(Long id) {
this.id = id;
}
public void setQuote(String quote) {
this.quote = quote;
}
@Override
public String toString() {
return "Value{" +
"id=" + id +
", quote='" + quote + '\'' +
'}';
}
}
```
This uses the same annotations but maps onto other data fields.
## Finishing the Application
The Initalizr creates a class with a `main()` method. The following listing shows the class the Initializr creates (at `src/main/java/com/example/consumingrest/ConsumingRestApplication.java`):
```
package com.example.consumingrest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConsumingRestApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
}
```
Now you need to add a few other things to the `ConsumingRestApplication` class to get it to show quotations from our RESTful source. You need to add:
- A logger, to send output to the log (the console, in this example).
- A `RestTemplate`, which uses the Jackson JSON processing library to process the incoming data.
- A `CommandLineRunner` that runs the `RestTemplate` (and, consequently, fetches our quotation) on startup.
The following listing shows the finished `ConsumingRestApplication` class (at `src/main/java/com/example/consumingrest/ConsumingRestApplication.java`):
```
package com.example.consumingrest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumingRestApplication {
private static final Logger log = LoggerFactory.getLogger(ConsumingRestApplication.class);
public static void main(String[] args) {
SpringApplication.run(ConsumingRestApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
Quote quote = restTemplate.getForObject(
"https://quoters.apps.pcfone.io/api/random", Quote.class);
log.info(quote.toString());
};
}
}
```
## Running the Application
You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you use Gradle, you can run the application by using `./gradlew bootRun`. Alternatively, you can build the JAR file by using `./gradlew build` and then run the JAR file, as follows:
```
java -jar build/libs/gs-consuming-rest-0.1.0.jar
```
If you use Maven, you can run the application by using `./mvnw spring-boot:run`. Alternatively, you can build the JAR file with `./mvnw clean package` and then run the JAR file, as follows:
```
java -jar target/gs-consuming-rest-0.1.0.jar
```
The steps described here create a runnable JAR. You can also build a classic WAR file.
You should see output similar to the following but with a random quotation:
```
2019-08-22 14:06:46.506 INFO 42940 --- [ main] c.e.c.ConsumingRestApplication : Quote{type='success', value=Value{id=1, quote='Working with Spring Boot is like pair-programming with the Spring developers.'}}
```
If you see an error that reads, `Could not extract response: no suitable HttpMessageConverter found for response type [class com.example.consumingrest.Quote]`, it is possible that you are in an environment that cannot connect to the backend service (which sends JSON if you can reach it). Maybe you are behind a corporate proxy. Try setting the `http.proxyHost` and `http.proxyPort` system properties to values appropriate for your environment.
## Summary
Congratulations! You have just developed a simple REST client by using Spring Boot.
原文链接: https://spring.io/guides/gs/consuming-rest/
## Developing Your First Spring Boot Application
This section describes how to develop a small “Hello World!” web application that highlights some of Spring Boot’s key features. We use Maven to build this project, since most IDEs support it.
Tip:
The [spring.io](https://spring.io/) web site contains many “Getting Started” [guides](https://spring.io/guides) that use Spring Boot. If you need to solve a specific problem, check there first.
You can shortcut the steps below by going to [start.spring.io](https://start.spring.io/) and choosing the "Web" starter from the dependencies searcher. Doing so generates a new project structure so that you can [start coding right away](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.first-application.code). Check the [start.spring.io user guide](https://github.com/spring-io/start.spring.io/blob/main/USING.adoc) for more details.
Before we begin, open a terminal and run the following commands to ensure that you have valid versions of Java and Maven installed:
```
$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
```
```
$ mvn -v
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Oracle Corporation
```
Note:
This sample needs to be created in its own directory. Subsequent instructions assume that you have created a suitable directory and that it is your current directory.
### Creating the POM
We need to start by creating a Maven `pom.xml` file. The `pom.xml` is the recipe that is used to build your project. Open your favorite text editor and add the following:
```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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
</parent>
<!-- Additional lines to be added here... -->
</project>
```
The preceding listing should give you a working build. You can test it by running `mvn package` (for now, you can ignore the “jar will be empty - no content was marked for inclusion!” warning).
Note:
At this point, you could import the project into an IDE (most modern Java IDEs include built-in support for Maven). For simplicity, we continue to use a plain text editor for this example.
### Adding Classpath Dependencies
Spring Boot provides a number of “Starters” that let you add jars to your classpath. Our applications for smoke tests use the `spring-boot-starter-parent` in the `parent` section of the POM. The `spring-boot-starter-parent` is a special starter that provides useful Maven defaults. It also provides a [`dependency-management`](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/using.html#using.build-systems.dependency-management) section so that you can omit `version` tags for “blessed” dependencies.
Other “Starters” provide dependencies that you are likely to need when developing a specific type of application. Since we are developing a web application, we add a `spring-boot-starter-web` dependency. Before that, we can look at what we currently have by running the following command:
```shell
$ mvn dependency:tree
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
```
The `mvn dependency:tree` command prints a tree representation of your project dependencies. You can see that `spring-boot-starter-parent` provides no dependencies by itself. To add the necessary dependencies, edit your `pom.xml` and add the `spring-boot-starter-web` dependency immediately below the `parent` section:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
```
If you run `mvn dependency:tree` again, you see that there are now a number of additional dependencies, including the Tomcat web server and Spring Boot itself.
### Writing the Code
To finish our application, we need to create a single Java file. By default, Maven compiles sources from `src/main/java`, so you need to create that directory structure and then add a file named `src/main/java/MyApplication.java` to contain the following code:
```java
@RestController
@EnableAutoConfiguration
public class MyApplication {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
Although there is not much code here, quite a lot is going on. We step through the important parts in the next few sections.
#### The @RestController and @RequestMapping Annotations
The first annotation on our `MyApplication` class is `@RestController`. This is known as a *stereotype* annotation. It provides hints for people reading the code and for Spring that the class plays a specific role. In this case, our class is a web `@Controller`, so Spring considers it when handling incoming web requests.
The `@RequestMapping` annotation provides “routing” information. It tells Spring that any HTTP request with the `/` path should be mapped to the `home` method. The `@RestController` annotation tells Spring to render the resulting string directly back to the caller.
Tip:
The `@RestController` and `@RequestMapping` annotations are Spring MVC annotations (they are not specific to Spring Boot). See the [MVC section](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc) in the Spring Reference Documentation for more details.
#### The @EnableAutoConfiguration Annotation
The second class-level annotation is `@EnableAutoConfiguration`. This annotation tells Spring Boot to “guess” how you want to configure Spring, based on the jar dependencies that you have added. Since `spring-boot-starter-web` added Tomcat and Spring MVC, the auto-configuration assumes that you are developing a web application and sets up Spring accordingly.
```
Starters and Auto-configuration
Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. You are free to pick and choose jar dependencies outside of the starters. Spring Boot still does its best to auto-configure your application.
```
#### The “main” Method
The final part of our application is the `main` method. This is a standard method that follows the Java convention for an application entry point. Our main method delegates to Spring Boot’s `SpringApplication` class by calling `run`. `SpringApplication` bootstraps our application, starting Spring, which, in turn, starts the auto-configured Tomcat web server. We need to pass `MyApplication.class` as an argument to the `run` method to tell `SpringApplication` which is the primary Spring component. The `args` array is also passed through to expose any command-line arguments.
### Running the Example
At this point, your application should work. Since you used the `spring-boot-starter-parent` POM, you have a useful `run` goal that you can use to start the application. Type `mvn spring-boot:run` from the root project directory to start the application. You should see output similar to the following:
```shell
$ mvn spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.4)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.222 seconds (JVM running for 6.514)
```
If you open a web browser to `localhost:8080`, you should see the following output:
```
Hello World!
```
To gracefully exit the application, press `ctrl-c`.
### Creating an Executable Jar
We finish our example by creating a completely self-contained executable jar file that we could run in production. Executable jars (sometimes called “fat jars”) are archives containing your compiled classes along with all of the jar dependencies that your code needs to run.
Executable jars and Java
Java does not provide a standard way to load nested jar files (jar files that are themselves contained within a jar). This can be problematic if you are looking to distribute a self-contained application.
To solve this problem, many developers use “uber” jars. An uber jar packages all the classes from all the application’s dependencies into a single archive. The problem with this approach is that it becomes hard to see which libraries are in your application. It can also be problematic if the same filename is used (but with different content) in multiple jars.
Spring Boot takes a [different approach](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/executable-jar.html#appendix.executable-jar) and lets you actually nest jars directly.
To create an executable jar, we need to add the `spring-boot-maven-plugin` to our `pom.xml`. To do so, insert the following lines just below the `dependencies` section:
```xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
```
Note:
The `spring-boot-starter-parent` POM includes `<executions>` configuration to bind the `repackage` goal. If you do not use the parent POM, you need to declare this configuration yourself. See the [plugin documentation](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#getting-started) for details.
Save your `pom.xml` and run `mvn package` from the command line, as follows:
```shell
$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.6.4:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
```
If you look in the `target` directory, you should see `myproject-0.0.1-SNAPSHOT.jar`. The file should be around 10 MB in size. If you want to peek inside, you can use `jar tvf`, as follows:
```shell
$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar
```
You should also see a much smaller file named `myproject-0.0.1-SNAPSHOT.jar.original` in the `target` directory. This is the original jar file that Maven created before it was repackaged by Spring Boot.
To run that application, use the `java -jar` command, as follows:
```shell
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.4)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.536 seconds (JVM running for 2.864)
```
As before, to exit the application, press `ctrl-c`.
原文链接: https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.first-application
\ No newline at end of file
......@@ -3,4 +3,3 @@
![2022-03-01-18-11-18](./initializr/2022-03-01-18-11-18.png)
原文链接: https://start.spring.io/
......@@ -48,4 +48,4 @@ The following guide may also be helpful:
- [Working a Getting Started guide with STS](https://spring.io/guides/gs/sts/)
原文链接: https://spring.io/guides/gs/intellij_idea/
\ No newline at end of file
原文链接: https://spring.io/guides/gs/intellij-idea/
\ No newline at end of file
## Introducing Spring Boot
Spring Boot helps you to create stand-alone, production-grade Spring-based applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
You can use Spring Boot to create Java applications that can be started by using `java -jar` or more traditional war deployments. We also provide a command line tool that runs “spring scripts”.
Our primary goals are:
- Provide a radically faster and widely accessible getting-started experience for all Spring development.
- Be opinionated out of the box but get out of the way quickly as requirements start to diverge from the defaults.
- Provide a range of non-functional features that are common to large classes of projects (such as embedded servers, security, metrics, health checks, and externalized configuration).
- Absolutely no code generation and no requirement for XML configuration.
原文链接: https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.introducing-spring-boot
\ No newline at end of file
# Building a RESTful Web Service
This guide walks you through the process of creating a “Hello, World” RESTful web service with Spring.
## What You Will Build
You will build a service that will accept HTTP GET requests at `http://localhost:8080/greeting`.
It will respond with a JSON representation of a greeting, as the following listing shows:
```
{"id":1,"content":"Hello, World!"}
```
You can customize the greeting with an optional `name` parameter in the query string, as the following listing shows:
```
http://localhost:8080/greeting?name=User
```
The `name` parameter value overrides the default value of `World` and is reflected in the response, as the following listing shows:
```
{"id":1,"content":"Hello, User!"}
```
## What You Need
- About 15 minutes
- A favorite text editor or IDE
- [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) or later
- [Gradle 4+](http://www.gradle.org/downloads) or [Maven 3.2+](https://maven.apache.org/download.cgi)
- You can also import the code straight into your IDE:
- [Spring Tool Suite (STS)](https://spring.io/guides/gs/sts)
- [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## How to complete this guide
Like most Spring [Getting Started guides](https://spring.io/guides), you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.
To **start from scratch**, move on to [Starting with Spring Initializr](https://spring.io/guides/gs/rest-service/#scratch).
To **skip the basics**, do the following:
- [Download](https://github.com/spring-guides/gs-rest-service/archive/main.zip) and unzip the source repository for this guide, or clone it using [Git](https://spring.io/understanding/Git): `git clone https://github.com/spring-guides/gs-rest-service.git`
- cd into `gs-rest-service/initial`
- Jump ahead to [Create a Resource Representation Class](https://spring.io/guides/gs/rest-service/#initial).
**When you finish**, you can check your results against the code in `gs-rest-service/complete`.
## Starting with Spring Initializr
You can use this [pre-initialized project](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.5.5&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=rest-service&name=rest-service&description=Demo project for Spring Boot&packageName=com.example.rest-service&dependencies=web) and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
To manually initialize the project:
1. Navigate to [https://start.spring.io](https://start.spring.io/). This service pulls in all the dependencies you need for an application and does most of the setup for you.
2. Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
3. Click **Dependencies** and select **Spring Web**.
4. Click **Generate**.
5. Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
```
If your IDE has the Spring Initializr integration, you can complete this process from your IDE.
```
```
You can also fork the project from Github and open it in your IDE or other editor.
```
## Create a Resource Representation Class
Now that you have set up the project and build system, you can create your web service.
Begin the process by thinking about service interactions.
The service will handle `GET` requests for `/greeting`, optionally with a `name` parameter in the query string. The `GET` request should return a `200 OK` response with JSON in the body that represents a greeting. It should resemble the following output:
```
{
"id": 1,
"content": "Hello, World!"
}
```
The `id` field is a unique identifier for the greeting, and `content` is the textual representation of the greeting.
To model the greeting representation, create a resource representation class. To do so, provide a plain old Java object with fields, constructors, and accessors for the `id` and `content` data, as the following listing (from `src/main/java/com/example/restservice/Greeting.java`) shows:
```
package com.example.restservice;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
```
This application uses the [Jackson JSON](https://github.com/FasterXML/jackson) library to automatically marshal instances of type `Greeting` into JSON. Jackson is included by default by the web starter.
## Create a Resource Controller
In Spring’s approach to building RESTful web services, HTTP requests are handled by a controller. These components are identified by the [`@RestController`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html) annotation, and the `GreetingController` shown in the following listing (from `src/main/java/com/example/restservice/GreetingController.java`) handles `GET` requests for `/greeting` by returning a new instance of the `Greeting` class:
```
package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
```
This controller is concise and simple, but there is plenty going on under the hood. We break it down step by step.
The `@GetMapping` annotation ensures that HTTP GET requests to `/greeting` are mapped to the `greeting()` method.
There are companion annotations for other HTTP verbs (e.g. `@PostMapping` for POST). There is also a `@RequestMapping` annotation that they all derive from, and can serve as a synonym (e.g. `@RequestMapping(method=GET)`).
`@RequestParam` binds the value of the query string parameter `name` into the `name` parameter of the `greeting()` method. If the `name` parameter is absent in the request, the `defaultValue` of `World` is used.
The implementation of the method body creates and returns a new `Greeting` object with `id` and `content` attributes based on the next value from the `counter` and formats the given `name` by using the greeting `template`.
A key difference between a traditional MVC controller and the RESTful web service controller shown earlier is the way that the HTTP response body is created. Rather than relying on a view technology to perform server-side rendering of the greeting data to HTML, this RESTful web service controller populates and returns a `Greeting` object. The object data will be written directly to the HTTP response as JSON.
This code uses Spring [`@RestController`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html) annotation, which marks the class as a controller where every method returns a domain object instead of a view. It is shorthand for including both `@Controller` and `@ResponseBody`.
The `Greeting` object must be converted to JSON. Thanks to Spring’s HTTP message converter support, you need not do this conversion manually. Because [Jackson 2](https://github.com/FasterXML/jackson) is on the classpath, Spring’s [`MappingJackson2HttpMessageConverter`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html) is automatically chosen to convert the `Greeting` instance to JSON.
`@SpringBootApplication` is a convenience annotation that adds all of the following:
- `@Configuration`: Tags the class as a source of bean definitions for the application context.
- `@EnableAutoConfiguration`: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if `spring-webmvc` is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a `DispatcherServlet`.
- `@ComponentScan`: Tells Spring to look for other components, configurations, and services in the `com/example` package, letting it find the controllers.
The `main()` method uses Spring Boot’s `SpringApplication.run()` method to launch an application. Did you notice that there was not a single line of XML? There is no `web.xml` file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.
### Build an executable JAR
You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.
If you use Gradle, you can run the application by using `./gradlew bootRun`. Alternatively, you can build the JAR file by using `./gradlew build` and then run the JAR file, as follows:
```
java -jar build/libs/gs-rest-service-0.1.0.jar
```
If you use Maven, you can run the application by using `./mvnw spring-boot:run`. Alternatively, you can build the JAR file with `./mvnw clean package` and then run the JAR file, as follows:
```
java -jar target/gs-rest-service-0.1.0.jar
```
The steps described here create a runnable JAR. You can also [build a classic WAR file](https://spring.io/guides/gs/convert-jar-to-war/).
Logging output is displayed. The service should be up and running within a few seconds.
## Test the Service
Now that the service is up, visit `http://localhost:8080/greeting`, where you should see:
```
{"id":1,"content":"Hello, World!"}
```
Provide a `name` query string parameter by visiting `http://localhost:8080/greeting?name=User`. Notice how the value of the `content` attribute changes from `Hello, World!` to `Hello, User!`, as the following listing shows:
```
{"id":2,"content":"Hello, User!"}
```
This change demonstrates that the `@RequestParam` arrangement in `GreetingController` is working as expected. The `name` parameter has been given a default value of `World` but can be explicitly overridden through the query string.
Notice also how the `id` attribute has changed from `1` to `2`. This proves that you are working against the same `GreetingController` instance across multiple requests and that its `counter` field is being incremented on each call as expected.
## Summary
Congratulations! You have just developed a RESTful web service with Spring.
原文链接: https://spring.io/guides/gs/rest-service/
\ No newline at end of file
# Getting Started with Java in VS Code
This tutorial shows you how to write and run Hello World program in Java with Visual Studio Code. It also covers a few advanced features, which you can explore by reading other documents in this section.
For an overview of the features available for Java in VS Code, see [Java Language Overview](https://code.visualstudio.com/docs/languages/java).
If you run into any issues when following this tutorial, you can contact us by entering an [issue](https://github.com/microsoft/vscode-java-pack/issues).
## Setting up VS Code for Java development
### Coding Pack for Java
To help you set up quickly, you can install the **Coding Pack for Java**, which includes VS Code, the Java Development Kit (JDK), and essential Java extensions. The Coding Pack can be used as a clean installation, or to update or repair an existing development environment.
[Install the Coding Pack for Java - Windows](https://aka.ms/vscode-java-installer-win)
[Install the Coding Pack for Java - macOS](https://aka.ms/vscode-java-installer-mac)
> **Note**: The Coding Pack for Java is only available for Windows and macOS. For other operating systems, you will need to manually install a JDK, VS Code, and Java extensions.
### Installing extensions
If you are an existing VS Code user, you can also add Java support by installing the [Extension Pack for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack), which includes these extensions:
- [Language Support for Java™ by Red Hat](https://marketplace.visualstudio.com/items?itemName=redhat.java)
- [Debugger for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-debug)
- [Test Runner for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-test)
- [Maven for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-maven)
- [Project Manager for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-dependency)
- [Visual Studio IntelliCode](https://marketplace.visualstudio.com/items?itemName=VisualStudioExptTeam.vscodeintellicode)
[Install the Extension Pack for Java](vscode:extension/vscjava.vscode-java-pack)
The [Extension Pack for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack) provides a Quick Start guide and tips for code editing and debugging. It also has a FAQ that answers some frequently asked questions. Use the command **Java: Tips for Beginners** from the Command Palette (Ctrl+Shift+P) to launch the guide.
![getting-started](./vscode_java/getting-started.png)
You can also install extensions separately. The **Extensions Guide** is provided to help you. You can launch the guide with the **Java: Extensions Guide** command.
For this tutorial, the only required extensions are:
- [Language Support for Java™ by Red Hat](https://marketplace.visualstudio.com/items?itemName=redhat.java)
- [Debugger for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-debug)
## Installing and setting up a Java Development Kit (JDK)
To use Java within Visual Studio Code, you need to install a Java Development Kit (JDK) on your local environment. JDK is a software development environment used for developing Java applications.
### Supported Java versions
The [Extension Pack for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack) supports Java version 1.5 or above.
> **Note**: To configure JDKs for your projects, see [Configure Runtime for Projects](https://code.visualstudio.com/docs/java/java-project#_configure-runtime-for-projects). To enable Java preview features, see [How can I use VS Code with new Java versions](https://code.visualstudio.com/docs/java/java-faq#_how-can-i-use-visual-studio-code-with-new-java-versions).
### Installing a Java Development Kit (JDK)
If you have never installed a JDK before and need to install one, we recommend you to choose from one of these sources:
- [Amazon Corretto](https://aws.amazon.com/corretto)
- [Azul Zulu](https://www.azul.com/downloads/?package=jdk)
- [Eclipse Adoptium's Temurin](https://adoptium.net/)
- [Microsoft Build of OpenJDK](https://www.microsoft.com/openjdk)
- [Oracle Java SE](https://www.oracle.com/java/technologies/javase-downloads.html)
- [Red Hat build of OpenJDK](https://developers.redhat.com/products/openjdk/download)
- [SapMachine](https://sapmachine.io/)
## Creating a source code file
Create a folder for your Java program and open the folder with VS Code. Then in VS Code, create a new file and save it with the name `Hello.java`. When you open that file, the Java Language Server automatically starts loading, and you should see a loading icon on the right side of the Status Bar. After it finishes loading, you will see a thumbs-up icon.
<video src="./vscode_java/JavaHelloWorld.Standalone.mp4"></video>
> **Note**: If you open a Java file in VS Code without opening its folder, the Java Language Server might not work properly.
VS Code will also try to figure out the correct package for the new type and fill the new file from a template. See [Create new file](https://code.visualstudio.com/docs/java/java-editing#_create-new-file).
You can also create a Java project using the **Java: Create Java Project** command. Bring up the **Command Palette** (Ctrl+Shift+P) and then type `java` to search for this command. After selecting the command, you will be prompted for the location and name of the project. You can also choose your build tool from this command.
<video src="./vscode_java/JavaHelloWorld.Project.mp4"></video>
Visual Studio Code also supports more complex Java projects — see [Project Management](https://code.visualstudio.com/docs/java/java-project).
## Editing source code
You can use code snippets to scaffold your classes and methods. VS Code also provides IntelliSense for code completion, and various refactor methods.
<video src="./vscode_java/edit-code.mp4"></video>
To learn more about editing Java, see [Java Editing](https://code.visualstudio.com/docs/java/java-editing).
## Running and debugging your program
To run and debug Java code, set a breakpoint, then either press F5 on your keyboard or use the **Run** > **Start Debugging** menu item. You can also use the **Run|Debug** CodeLens option in the editor. After the code compiles, you can see all your variables and threads in the Run view.
<video src="./vscode_java/run-debug.mp4"></video>
The debugger also supports advanced features such as [Hot Code Replace](https://code.visualstudio.com/docs/java/java-debugging#_hot-code-replace) and conditional breakpoints.
For more information, see [Java Debugging](https://code.visualstudio.com/docs/java/java-debugging).
## More features
The editor also has many more capabilities to assist with your Java workload.
- [Editing Java](https://code.visualstudio.com/docs/java/java-editing) explains how to navigate and edit Java in more details
- [Debugging](https://code.visualstudio.com/docs/java/java-debugging) illustrates all the key features of the Java Debugger
- [Testing](https://code.visualstudio.com/docs/java/java-testing) provides comprehensive support for JUnit and TestNG framework
- [Java Project Management](https://code.visualstudio.com/docs/java/java-project) shows you how to use a project view and work with Maven
- [Spring Boot](https://code.visualstudio.com/docs/java/java-spring-boot) and [Tomcat and Jetty](https://code.visualstudio.com/docs/java/java-tomcat-jetty) demonstrate great framework support
- [Java Web Apps](https://code.visualstudio.com/docs/java/java-webapp) shows how to work with Java Web App in VS Code
原文链接: https://code.visualstudio.com/docs/java/java-tutorial
\ No newline at end of file
## 开发你的第一个 Spring Boot 应用程序
本节介绍如何开发一个小的“Hello World!” 突出 Spring Boot 的一些关键特性的 web 应用程序。我们使用 Maven 来构建这个项目,因为大多数 IDE 都支持它。
Tip:
spring.io网站包含许多使用 Spring Boot 的“入门”[指南](https://spring.io/guides)[](https://spring.io/)如果您需要解决特定问题,请先检查那里。
您可以通过转到[start.spring.io](https://start.spring.io/)并从依赖项搜索器中选择“Web”启动器来简化以下步骤。这样做会生成一个新的项目结构,以便您可以[立即开始编码](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.first-application.code)。查看[start.spring.io 用户指南](https://github.com/spring-io/start.spring.io/blob/main/USING.adoc)了解更多详情。
在我们开始之前,打开一个终端并运行以下命令以确保您安装了有效版本的 Java 和 Maven:
```
$ java -version
java version "1.8.0_102"
Java(TM) SE Runtime Environment (build 1.8.0_102-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.102-b14, mixed mode)
```
```
$ mvn -v
Apache Maven 3.5.4 (1edded0938998edf8bf061f1ceb3cfdeccf443fe; 2018-06-17T14:33:14-04:00)
Maven home: /usr/local/Cellar/maven/3.3.9/libexec
Java version: 1.8.0_102, vendor: Oracle Corporation
```
Note:
此示例需要在其自己的目录中创建。后续说明假定您已经创建了一个合适的目录并且它是您的当前目录。
### 创建 POM
我们需要从创建一个 Maven`pom.xml`文件开始。这`pom.xml`是用于构建项目的配方。打开您喜欢的文本编辑器并添加以下内容:
```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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>myproject</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.4</version>
</parent>
<!-- Additional lines to be added here... -->
</project>
```
前面的清单应该给你一个工作构建。您可以通过运行对其进行测试`mvn package`(现在,您可以忽略“jar 将为空 - 没有内容被标记为包含!”警告)。
Note:
此时,您可以将项目导入 IDE(大多数现代 Java IDE 都包含对 Maven 的内置支持)。为简单起见,我们在此示例中继续使用纯文本编辑器。
### 添加类路径依赖项
Spring Boot 提供了许多“启动器”,可让您将 jars 添加到类路径中。我们的烟雾测试应用程序使用POM 部分中的`spring-boot-starter-parent``parent``spring-boot-starter-parent`是一个特殊的启动器,提供有用的 Maven 默认值。它还提供了一个[`dependency-management`](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/using.html#using.build-systems.dependency-management)部分,以便您可以省略`version`“祝福”依赖项的标签。
其他“Starters”提供了您在开发特定类型的应用程序时可能需要的依赖项。由于我们正在开发 Web 应用程序,因此我们添加了一个`spring-boot-starter-web`依赖项。在此之前,我们可以通过运行以下命令查看我们当前拥有的内容:
```shell
$ mvn dependency:tree
[INFO] com.example:myproject:jar:0.0.1-SNAPSHOT
```
`mvn dependency:tree`命令打印项目依赖项的树表示。您可以看到它`spring-boot-starter-parent`本身不提供任何依赖项。要添加必要的依赖项,请编辑您的并在该部分正下方`pom.xml`添加依赖项:`spring-boot-starter-web parent`
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
```
如果`mvn dependency:tree`再次运行,您会看到现在有许多附加依赖项,包括 Tomcat Web 服务器和 Spring Boot 本身。
### 编写代码
为了完成我们的应用程序,我们需要创建一个 Java 文件。默认情况下,Maven 从 编译源代码`src/main/java`,因此您需要创建该目录结构,然后添加一个名为`src/main/java/MyApplication.java`包含以下代码的文件:
```java
@RestController
@EnableAutoConfiguration
public class MyApplication {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
虽然这里没有太多代码,但有很多事情正在发生。我们将在接下来的几节中逐步介绍重要部分。
#### @RestController 和 @RequestMapping 注解
`MyApplication`我们类的第一个注释是`@RestController`. 这称为*构造型*注释。它为阅读代码的人和 Spring 提供了类扮演特定角色的提示。在这种情况下,我们的类是一个 web `@Controller`,因此 Spring 在处理传入的 Web 请求时会考虑它。
`@RequestMapping`注释提供“路由”信息。它告诉 Spring 任何带有该`/`路径的 HTTP 请求都应该映射到该`home`方法。注释告诉 Spring将`@RestController`结果字符串直接呈现给调用者。
Tip:
和注释是 Spring MVC 注释`@RestController``@RequestMapping`它们不是特定于 Spring Boot)。有关详细信息,请参阅 Spring 参考文档中的[MVC 部分](https://docs.spring.io/spring-framework/docs/5.3.16/reference/html/web.html#mvc)
#### @EnableAutoConfiguration 注解
第二个类级别的注释是`@EnableAutoConfiguration`. 这个注解告诉 Spring Boot 根据你添加的 jar 依赖来“猜测”你想如何配置 Spring。由于`spring-boot-starter-web`添加了 Tomcat 和 Spring MVC,自动配置假定您正在开发 Web 应用程序并相应地设置 Spring。
```
启动器和自动配置
自动配置旨在与“启动器”很好地配合使用,但这两个概念并没有直接联系。您可以自由选择启动器之外的 jar 依赖项。Spring Boot 仍然尽力自动配置您的应用程序。
```
#### “主要”方法
我们应用程序的最后一部分是`main`方法。这是一种遵循应用程序入口点的 Java 约定的标准方法。我们的 main 方法通过调用委托给 Spring Boot 的`SpringApplication``run``SpringApplication`引导我们的应用程序,启动 Spring,然后启动自动配置的 Tomcat Web 服务器。我们需要将`MyApplication.class`作为参数传递给该`run`方法,以判断`SpringApplication`哪个是主要的 Spring 组件。该`args`数组也被传递以公开任何命令行参数。
### 运行示例
此时,您的应用程序应该可以工作了。由于您使用了`spring-boot-starter-parent`POM,因此您有一个有用的`run`目标,可用于启动应用程序。`mvn spring-boot:run`从根项目目录键入以启动应用程序。您应该会看到类似于以下内容的输出:
```shell
$ mvn spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.4)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.222 seconds (JVM running for 6.514)
```
如果您打开 Web 浏览器`localhost:8080`,您应该会看到以下输出:
```
Hello World!
```
要优雅地退出应用程序,请按`ctrl-c`
### 创建可执行 Jar
我们通过创建一个可以在生产中运行的完全独立的可执行 jar 文件来完成我们的示例。可执行 jars(有时称为“fat jars”)是包含已编译类以及代码需要运行的所有 jar 依赖项的存档。
可执行 jar 和 Java
Java 不提供加载嵌套 jar 文件(本身包含在 jar 中的 jar 文件)的标准方法。如果您希望分发一个独立的应用程序,这可能会出现问题。
为了解决这个问题,许多开发人员使用“超级”罐子。一个 uber jar 将所有应用程序依赖项中的所有类打包到一个存档中。这种方法的问题是很难看到应用程序中有哪些库。如果在多个 jar 中使用相同的文件名(但内容不同),也可能会出现问题。
Spring Boot 采用了[不同的方法](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/executable-jar.html#appendix.executable-jar),让您实际上可以直接嵌套 jar。
`spring-boot-maven-plugin`要创建一个可执行的 jar,我们需要将`pom.xml`. 为此,请在该`dependencies`部分下方插入以下行:
```xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
```
Note:
`spring-boot-starter-parent`POM 包含`<executions>`绑定`repackage`目标 的配置。如果不使用父 POM,则需要自己声明此配置。有关详细信息,请参阅[插件文档](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#getting-started)
保存`pom.xml`并从命令行运行`mvn package`,如下:
```shell
$ mvn package
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myproject 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] .... ..
[INFO] --- maven-jar-plugin:2.4:jar (default-jar) @ myproject ---
[INFO] Building jar: /Users/developer/example/spring-boot-example/target/myproject-0.0.1-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:2.6.4:repackage (default) @ myproject ---
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
```
如果您查看`target`目录,您应该会看到`myproject-0.0.1-SNAPSHOT.jar`. 该文件的大小应约为 10 MB。如果你想偷看里面,你可以使用`jar tvf`,如下:
```shell
$ jar tvf target/myproject-0.0.1-SNAPSHOT.jar
```
`myproject-0.0.1-SNAPSHOT.jar.original`您还应该在目录中看到一个小得多的文件`target`。这是Maven在被Spring Boot重新打包之前创建的原始jar文件。
和以前一样,要退出应用程序,请按`ctrl-c`
```shell
$ java -jar target/myproject-0.0.1-SNAPSHOT.jar
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.6.4)
....... . . .
....... . . . (log output here)
....... . . .
........ Started MyApplication in 2.536 seconds (JVM running for 2.864)
```
As before, to exit the application, press `ctrl-c`.
原文链接: https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.first-application
\ No newline at end of file
# Spring initializr 构建项目
# 脚手架
![2022-03-01-18-11-18](./initializr/2022-03-01-18-11-18.png)
......
......@@ -48,4 +48,4 @@ IntelliJ IDEA 将创建一个项目,其中包含准备运行的指南中的所
- [使用 STS 编写入门指南](https://spring.io/guides/gs/sts/)https://spring.io/guides/gs/sts/)
原文链接: https://spring.io/guides/gs/intellij_idea/
\ No newline at end of file
原文链接: https://spring.io/guides/gs/intellij-idea/
\ No newline at end of file
## Spring Boot 介绍
Spring Boot 可帮助您创建可以运行的独立的、生产级的基于 Spring 的应用程序。我们对 Spring 平台和第三方库持固执己见的看法,以便您可以轻松上手。大多数 Spring Boot 应用程序只需要很少的 Spring 配置。
您可以使用 Spring Boot 创建可以通过使用`java -jar`或更传统的战争部署启动的 Java 应用程序。我们还提供了一个运行“spring 脚本”的命令行工具。
我们的主要目标是:
- 为所有 Spring 开发提供从根本上更快且可广泛访问的入门体验。
- 开箱即用,但随着需求开始偏离默认值,请迅速摆脱困境。
- 提供大类项目(例如嵌入式服务器、安全性、指标、健康检查和外部化配置)通用的一系列非功能性特性。
- 绝对没有代码生成,也不需要 XML 配置。
原文链接: https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.introducing-spring-boot
\ No newline at end of file
# 构建 RESTful Web 服务
本指南将引导您完成使用 Spring 创建“Hello, World”RESTful Web 服务的过程。
## 你将建造什么
您将构建一个接受 HTTP GET 请求的服务`http://localhost:8080/greeting`
它将以问候语的 JSON 表示形式进行响应,如以下清单所示:
```
{"id":1,"content":"Hello, World!"}
```
您可以在查询字符串中使用可选`name`参数自定义问候语,如以下清单所示:
```
http://localhost:8080/greeting?name=User
```
`name`参数值覆盖默认值`World`并反映在响应中,如以下清单所示:
```
{"id":1,"content":"Hello, User!"}
```
## 你需要什么
- 约15分钟
- 最喜欢的文本编辑器或 IDE
- [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html)或更高版本
- [Gradle 4+](http://www.gradle.org/downloads)[Maven 3.2+](https://maven.apache.org/download.cgi)
- 您还可以将代码直接导入 IDE:
- [弹簧工具套件 (STS)](https://spring.io/guides/gs/sts)
- [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## 如何完成本指南
像大多数 Spring[入门指南](https://spring.io/guides)一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到工作代码。
**从头开始**,请继续[从 Spring Initializr 开始](https://spring.io/guides/gs/rest-service/#scratch)
**跳过基础知识**,请执行以下操作:
- [下载](https://github.com/spring-guides/gs-rest-service/archive/main.zip)并解压缩本指南的源存储库,或使用[Git](https://spring.io/understanding/Git)克隆它:`git clone https://github.com/spring-guides/gs-rest-service.git`
- 光盘进入`gs-rest-service/initial`
- 继续[创建资源表示类](https://spring.io/guides/gs/rest-service/#initial)
**完成后**,您可以对照中的代码检查结果`gs-rest-service/complete`
## 从 Spring Initializr 开始
您可以使用这个[预先初始化的项目](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.5.5&packaging=jar&jvmVersion=11&groupId=com.example&artifactId=rest-service&name=rest-service&description=Demo project for Spring Boot&packageName=com.example.rest-service&dependencies=web)并单击 Generate 下载 ZIP 文件。此项目配置为适合本教程中的示例。
手动初始化项目:
1. 导航到[https://start.spring.io](https://start.spring.io/)。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。
2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
3. 单击**Dependencies**并选择**Spring Web**
4. 单击**生成**
5. 下载生成的 ZIP 文件,该文件是根据您的选择配置的 Web 应用程序的存档。
```
如果您的 IDE 具有 Spring Initializr 集成,您可以从您的 IDE 完成此过程。
```
```
你也可以从 Github 上 fork 项目并在你的 IDE 或其他编辑器中打开它。
```
## 创建资源表示类
现在您已经设置了项目和构建系统,您可以创建您的 Web 服务。
从考虑服务交互开始这个过程。
该服务将处理对 的`GET`请求`/greeting`,可以选择`name`在查询字符串中使用参数。该`GET`请求应`200 OK`在表示问候的正文中返回带有 JSON 的响应。它应该类似于以下输出:
```
{
"id": 1,
"content": "Hello, World!"
}
```
`id`字段是问候语的唯一标识符,是问候语`content`的文本表示。
要对问候表示建模,请创建一个资源表示类。为此,请提供一个普通的旧 Java 对象,其中包含用于`id``content`数据的字段、构造函数和访问器,如以下清单(来自`src/main/java/com/example/restservice/Greeting.java`)所示:
```
package com.example.restservice;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
```
此应用程序使用[Jackson JSON](https://github.com/FasterXML/jackson)库将类型的实例自动编组`Greeting`为 JSON。网络启动器默认包含 Jackson。
## 创建资源控制器
在 Spring 构建 RESTful Web 服务的方法中,HTTP 请求由控制器处理。这些组件由[`@RestController`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html)注释标识,`GreetingController`下面的清单 (from )通过返回类的新实例来`src/main/java/com/example/restservice/GreetingController.java`处理`GET`请求:`/greeting``Greeting`
```
package com.example.restservice;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
```
这个控制器简洁明了,但引擎盖下有很多事情要做。我们一步一步分解。
`@GetMapping`注释确保 HTTP GET 请求`/greeting`映射到`greeting()`方法。
有其他 HTTP 动词的伴随注释(例如`@PostMapping`POST)。还有一个`@RequestMapping`它们都源自的注释,并且可以用作同义词(例如`@RequestMapping(method=GET)`)。
`@RequestParam`将查询字符串参数的值绑定`name`到方法的`name`参数中`greeting()`。如果`name`请求中没有参数,则使用`defaultValue`of `World`
方法体的实现创建并返回一个新`Greeting`对象,该对象具有`id``content`基于下一个值的属性,并使用 greeting`counter`格式化给定的格式。`name``template`
传统 MVC 控制器和前面显示的 RESTful Web 服务控制器之间的一个关键区别是 HTTP 响应主体的创建方式。这个 RESTful Web 服务控制器不是依靠视图技术来执行服务器端将问候数据呈现为 HTML,而是填充并返回一个`Greeting`对象。对象数据将作为 JSON 直接写入 HTTP 响应。
此代码使用 Spring[`@RestController`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RestController.html)注释,它将类标记为控制器,其中每个方法都返回域对象而不是视图。它是同时包含`@Controller`和的简写`@ResponseBody`
`Greeting`对象必须转换为 JSON。感谢 Spring 的 HTTP 消息转换器支持,您无需手动进行此转换。因为[Jackson 2](https://github.com/FasterXML/jackson)在类路径上,所以会自动选择 Spring[`MappingJackson2HttpMessageConverter`](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.html)`Greeting`实例转换为 JSON。
`@SpringBootApplication`是一个方便的注释,它添加了以下所有内容:
- `@Configuration`: 将类标记为应用程序上下文的 bean 定义源。
- `@EnableAutoConfiguration`:告诉 Spring Boot 根据类路径设置、其他 bean 和各种属性设置开始添加 bean。例如,如果`spring-webmvc`位于类路径上,则此注释将应用程序标记为 Web 应用程序并激活关键行为,例如设置`DispatcherServlet`.
- `@ComponentScan`: 告诉 Spring 在包中查找其他组件、配置和服务`com/example`,让它找到控制器。
`main()`方法使用 Spring Boot 的`SpringApplication.run()`方法来启动应用程序。您是否注意到没有一行 XML?也没有`web.xml`文件。这个 Web 应用程序是 100% 纯 Java,您不必处理任何管道或基础设施的配置。
### 构建一个可执行的 JAR
您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的单个可执行 JAR 文件并运行它。构建可执行 jar 可以在整个开发生命周期、跨不同环境等中轻松地作为应用程序交付、版本化和部署服务。
如果您使用 Gradle,则可以使用`./gradlew bootRun`. 或者,您可以使用构建 JAR 文件`./gradlew build`,然后运行 JAR 文件,如下所示:
```
java -jar build/libs/gs-rest-service-0.1.0.jar
```
如果您使用 Maven,则可以使用`./mvnw spring-boot:run`. 或者,您可以使用构建 JAR 文件,`./mvnw clean package`然后运行该 JAR 文件,如下所示:
```
java -jar target/gs-rest-service-0.1.0.jar
```
此处描述的步骤创建了一个可运行的 JAR。您还可以[构建经典的 WAR 文件](https://spring.io/guides/gs/convert-jar-to-war/)
显示记录输出。该服务应在几秒钟内启动并运行。
## 测试服务
现在服务已经启动,访问`http://localhost:8080/greeting`,您应该会看到:
```
{"id":1,"content":"Hello, World!"}
```
通过访问提供`name`查询字符串参数`http://localhost:8080/greeting?name=User``content`请注意属性的值如何从`Hello, World!`变为`Hello, User!`,如以下清单所示:
```
{"id":2,"content":"Hello, User!"}
```
这一变化表明,`@RequestParam`安排在`GreetingController`按预期工作。该`name`参数已被赋予默认值,`World`但可以通过查询字符串显式覆盖。
还要注意`id`属性是如何从`1`变为 的`2`。这证明您正在`GreetingController`跨多个请求处理同一个实例,并且其`counter`字段在每次调用时都按预期递增。
## 概括
恭喜!您刚刚使用 Spring 开发了一个 RESTful Web 服务。
原文链接: https://spring.io/guides/gs/rest-service/
\ No newline at end of file
# 在 VS Code 中开始使用 Java
本教程向您展示如何使用 Visual Studio Code 在 Java 中编写和运行 Hello World 程序。它还涵盖了一些高级功能,您可以通过阅读本节中的其他文档来探索这些功能。
有关 VS Code 中可用于 Java 的功能的概述,请参阅[Java 语言概述](https://code.visualstudio.com/docs/languages/java)
如果您在学习本教程时遇到任何问题,可以通过输入[问题](https://github.com/microsoft/vscode-java-pack/issues)与我们联系。
## 为 Java 开发设置 VS Code
### Java 编码包
为了帮助您快速设置,您可以安装**Coding Pack for Java**,其中包括 VS Code、Java 开发工具包 (JDK) 和基本的 Java 扩展。Coding Pack 可用作全新安装,或用于更新或修复现有开发环境。
[安装适用于 Java 的编码包 - Windows](https://aka.ms/vscode-java-installer-win)
[安装适用于 Java 的编码包 - macOS](https://aka.ms/vscode-java-installer-mac)
> **注意**:Java 编码包仅适用于 Windows 和 macOS。对于其他操作系统,您将需要手动安装 JDK、VS Code 和 Java 扩展。
### 安装扩展
如果您是现有的 VS Code 用户,还可以通过安装[Extension Pack for Java](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack)来添加 Java 支持,其中包括以下扩展:
- [Red Hat 对 Java™ 的语言支持](https://marketplace.visualstudio.com/items?itemName=redhat.java)
- [Java 调试器](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-debug)
- [Java 的测试运行器](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-test)
- [用于 Java 的 Maven](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-maven)
- [Java 项目经理](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-dependency)
- [Visual Studio 智能代码](https://marketplace.visualstudio.com/items?itemName=VisualStudioExptTeam.vscodeintellicode)
[安装 Java 扩展包](vscode:extension/vscjava.vscode-java-pack)
[Java 扩展包](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack)提供了快速入门指南和代码编辑和调试技巧。它还有一个常见问题解答,可以回答一些常见问题。使用命令选项板 ( Ctrl+Shift+P ) 中的命令**Java: Tips for Beginners**来启动指南。
![getting-started](./vscode_java/getting-started.png)
您也可以单独安装扩展。**扩展指南**旨在帮助您。您可以使用**Java: Extensions Guide**命令启动该指南。
对于本教程,唯一需要的扩展是:
- [Red Hat 对 Java™ 的语言支持](https://marketplace.visualstudio.com/items?itemName=redhat.java)
- [Java 调试器](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-debug)
## 安装和设置 Java 开发工具包 (JDK)
要在 Visual Studio Code 中使用 Java,您需要在本地环境中安装 Java 开发工具包 (JDK)。JDK是用于开发Java应用程序的软件开发环境。
### 支持的 Java 版本
[Java 扩展包](https://marketplace.visualstudio.com/items?itemName=vscjava.vscode-java-pack)支持Java 1.5 或更高版本。
> **注意**:要为您的项目配置 JDK,请参阅[为项目配置运行时](https://code.visualstudio.com/docs/java/java-project#_configure-runtime-for-projects)。要启用 Java 预览功能,请参阅[如何将 VS Code 与新的 Java 版本一起使用](https://code.visualstudio.com/docs/java/java-faq#_how-can-i-use-visual-studio-code-with-new-java-versions)。
### 安装 Java 开发工具包 (JDK)
如果您以前从未安装过 JDK 并且需要安装一个,我们建议您从以下来源之一中进行选择:
- [亚马逊 Corretto](https://aws.amazon.com/corretto)
- [阿祖尔祖鲁](https://www.azul.com/downloads/?package=jdk)
- [Eclipse Adoptium 的 Temurin](https://adoptium.net/)
- [OpenJDK 的 Microsoft 构建](https://www.microsoft.com/openjdk)
- [甲骨文 Java SE](https://www.oracle.com/java/technologies/javase-downloads.html)
- [Red Hat 构建的 OpenJDK](https://developers.redhat.com/products/openjdk/download)
- [树液机](https://sapmachine.io/)
## 创建源代码文件
为您的 Java 程序创建一个文件夹并使用 VS Code 打开该文件夹。然后在 VS Code 中,创建一个新文件并将其保存为`Hello.java`. 当您打开该文件时,Java 语言服务器会自动开始加载,您应该会在状态栏的右侧看到一个加载图标。加载完成后,您将看到一个竖起大拇指的图标。
<video src="./vscode_java/JavaHelloWorld.Standalone.mp4"></video>
> **注意**:如果您在 VS Code 中打开 Java 文件而不打开其文件夹,Java 语言服务器可能无法正常工作。
VS Code 还将尝试为新类型找出正确的包,并从模板中填充新文件。请参阅[创建新文件](https://code.visualstudio.com/docs/java/java-editing#_create-new-file)
您还可以使用**Java:Create Java Project**命令创建 Java 项目。调出**命令面板** ( Ctrl+Shift+P ),然后键入`java`以搜索此命令。选择命令后,系统会提示您输入项目的位置和名称。您还可以从此命令中选择构建工具。
<video src="./vscode_java/JavaHelloWorld.Project.mp4"></video>
Visual Studio Code 还支持更复杂的 Java 项目 - 请参阅[项目管理](https://code.visualstudio.com/docs/java/java-project)
## 编辑源代码
您可以使用代码片段来搭建您的类和方法。VS Code 还提供了用于代码完成的 IntelliSense,以及各种重构方法。
<video src="./vscode_java/edit-code.mp4"></video>
要了解有关编辑 Java 的更多信息,请参阅[Java 编辑](https://code.visualstudio.com/docs/java/java-editing)
## 运行和调试你的程序
要运行和调试 Java 代码,请设置断点,然后按键盘上的F5或使用**Run** > **Start Debugging**菜单项。您还可以在编辑器中使用**Run|Debug** CodeLens 选项。代码编译后,您可以在 Run 视图中看到所有变量和线程。
<video src="./vscode_java/run-debug.mp4"></video>
调试器还支持[热代码替换](https://code.visualstudio.com/docs/java/java-debugging#_hot-code-replace)和条件断点等高级功能。
有关详细信息,请参阅[Java 调试](https://code.visualstudio.com/docs/java/java-debugging)
## 更多功能
该编辑器还具有更多功能来帮助您处理 Java 工作负载。
- [编辑 Java](https://code.visualstudio.com/docs/java/java-editing)更详细地解释了如何导航和编辑 Java
- [调试](https://code.visualstudio.com/docs/java/java-debugging)说明了 Java 调试器的所有关键特性
- [测试](https://code.visualstudio.com/docs/java/java-testing)为 JUnit 和 TestNG 框架提供全面的支持
- [Java 项目管理](https://code.visualstudio.com/docs/java/java-project)向您展示如何使用项目视图和使用 Maven
- [Spring Boot](https://code.visualstudio.com/docs/java/java-spring-boot)[Tomcat 和 Jetty](https://code.visualstudio.com/docs/java/java-tomcat-jetty)展示了出色的框架支持
- [Java Web Apps](https://code.visualstudio.com/docs/java/java-webapp)展示了如何在 VS Code 中使用 Java Web App
原文链接: https://code.visualstudio.com/docs/java/java-tutorial
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册