提交 226e744a 编写于 作者: 茶陵後's avatar 茶陵後 👍

#1 临时移除en文件夹

上级 0e8651d3
# 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
# Spring initializr
![2022-03-01-18-11-18](./initializr/2022-03-01-18-11-18.png)
原文链接: https://start.spring.io/
## Installing Spring Boot
Spring Boot can be used with “classic” Java development tools or installed as a command line tool. Either way, you need [Java SDK v1.8](https://www.java.com/) or higher. Before you begin, you should check your current Java installation by using the following command:
```
$ java -version
```
If you are new to Java development or if you want to experiment with Spring Boot, you might want to try the [Spring Boot CLI](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.installing.cli) (Command Line Interface) first. Otherwise, read on for “classic” installation instructions.
### Installation Instructions for the Java Developer
You can use Spring Boot in the same way as any standard Java library. To do so, include the appropriate `spring-boot-*.jar` files on your classpath. Spring Boot does not require any special tools integration, so you can use any IDE or text editor. Also, there is nothing special about a Spring Boot application, so you can run and debug a Spring Boot application as you would any other Java program.
Although you *could* copy Spring Boot jars, we generally recommend that you use a build tool that supports dependency management (such as Maven or Gradle).
#### Maven Installation
Spring Boot is compatible with Apache Maven 3.3 or above. If you do not already have Maven installed, you can follow the instructions at [maven.apache.org](https://maven.apache.org/).
Tip:
On many operating systems, Maven can be installed with a package manager. If you use OSX Homebrew, try `brew install maven`. Ubuntu users can run `sudo apt-get install maven`. Windows users with [Chocolatey](https://chocolatey.org/) can run `choco install maven` from an elevated (administrator) prompt.
Spring Boot dependencies use the `org.springframework.boot` `groupId`. Typically, your Maven POM file inherits from the `spring-boot-starter-parent` project and declares dependencies to one or more [“Starters”](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/using.html#using.build-systems.starters). Spring Boot also provides an optional [Maven plugin](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/build-tool-plugins.html#build-tool-plugins.maven) to create executable jars.
More details on getting started with Spring Boot and Maven can be found in the [Getting Started section](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/#getting-started) of the Maven plugin’s reference guide.
#### Gradle Installation
Spring Boot is compatible with Gradle 6.8, 6.9, and 7.x. If you do not already have Gradle installed, you can follow the instructions at [gradle.org](https://gradle.org/).
Spring Boot dependencies can be declared by using the `org.springframework.boot` `group`. Typically, your project declares dependencies to one or more [“Starters”](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/using.html#using.build-systems.starters). Spring Boot provides a useful [Gradle plugin](https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/build-tool-plugins.html#build-tool-plugins.gradle) that can be used to simplify dependency declarations and to create executable jars.
```
Gradle Wrapper
The Gradle Wrapper provides a nice way of “obtaining” Gradle when you need to build a project. It is a small script and library that you commit alongside your code to bootstrap the build process. See docs.gradle.org/current/userguide/gradle_wrapper.html for details.
```
More details on getting started with Spring Boot and Gradle can be found in the [Getting Started section](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/#getting-started) of the Gradle plugin’s reference guide.
### Installing the Spring Boot CLI
The Spring Boot CLI (Command Line Interface) is a command line tool that you can use to quickly prototype with Spring. It lets you run [Groovy](https://groovy-lang.org/) scripts, which means that you have a familiar Java-like syntax without so much boilerplate code.
You do not need to use the CLI to work with Spring Boot, but it is a quick way to get a Spring application off the ground without an IDE.
#### Manual Installation
You can download the Spring CLI distribution from the Spring software repository:
- [spring-boot-cli-2.6.4-bin.zip](https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.6.4/spring-boot-cli-2.6.4-bin.zip)
- [spring-boot-cli-2.6.4-bin.tar.gz](https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/2.6.4/spring-boot-cli-2.6.4-bin.tar.gz)
Cutting edge [snapshot distributions](https://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/) are also available.
Once downloaded, follow the [INSTALL.txt](https://raw.githubusercontent.com/spring-projects/spring-boot/v2.6.4/spring-boot-project/spring-boot-cli/src/main/content/INSTALL.txt) instructions from the unpacked archive. In summary, there is a `spring` script (`spring.bat` for Windows) in a `bin/` directory in the `.zip` file. Alternatively, you can use `java -jar` with the `.jar` file (the script helps you to be sure that the classpath is set correctly).
#### Installation with SDKMAN!
SDKMAN! (The Software Development Kit Manager) can be used for managing multiple versions of various binary SDKs, including Groovy and the Spring Boot CLI. Get SDKMAN! from [sdkman.io](https://sdkman.io/) and install Spring Boot by using the following commands:
```
$ sdk install springboot
$ spring --version
Spring CLI v2.6.4
```
If you develop features for the CLI and want access to the version you built, use the following commands:
```
$ sdk install springboot dev /path/to/spring-boot/spring-boot-cli/target/spring-boot-cli-2.6.4-bin/spring-2.6.4/
$ sdk default springboot dev
$ spring --version
Spring CLI v2.6.4
```
The preceding instructions install a local instance of `spring` called the `dev` instance. It points at your target build location, so every time you rebuild Spring Boot, `spring` is up-to-date.
You can see it by running the following command:
```
$ sdk ls springboot
================================================================================
Available Springboot Versions
================================================================================
> + dev
* 2.6.4
================================================================================
+ - local version
* - installed
> - currently in use
================================================================================
```
#### OSX Homebrew Installation
If you are on a Mac and use [Homebrew](https://brew.sh/), you can install the Spring Boot CLI by using the following commands:
```
$ brew tap spring-io/tap
$ brew install spring-boot
```
Homebrew installs `spring` to `/usr/local/bin`.
Note:
If you do not see the formula, your installation of brew might be out-of-date. In that case, run `brew update` and try again.
#### MacPorts Installation
If you are on a Mac and use [MacPorts](https://www.macports.org/), you can install the Spring Boot CLI by using the following command:
```
$ sudo port install spring-boot-cli
```
#### Command-line Completion
The Spring Boot CLI includes scripts that provide command completion for the [BASH](https://en.wikipedia.org/wiki/Bash_(Unix_shell)) and [zsh](https://en.wikipedia.org/wiki/Z_shell) shells. You can `source` the script (also named `spring`) in any shell or put it in your personal or system-wide bash completion initialization. On a Debian system, the system-wide scripts are in `/shell-completion/bash` and all scripts in that directory are executed when a new shell starts. For example, to run the script manually if you have installed by using SDKMAN!, use the following commands:
```
$ . ~/.sdkman/candidates/springboot/current/shell-completion/bash/spring
$ spring <HIT TAB HERE>
grab help jar run test version
```
Note:
If you install the Spring Boot CLI by using Homebrew or MacPorts, the command-line completion scripts are automatically registered with your shell.
#### Windows Scoop Installation
If you are on a Windows and use [Scoop](https://scoop.sh/), you can install the Spring Boot CLI by using the following commands:
```
> scoop bucket add extras
> scoop install springboot
```
Scoop installs `spring` to `~/scoop/apps/springboot/current/bin`.
Note:
If you do not see the app manifest, your installation of scoop might be out-of-date. In that case, run `scoop update` and try again.
#### Quick-start Spring CLI Example
You can use the following web application to test your installation. To start, create a file called `app.groovy`, as follows:
```
@RestController
class ThisWillActuallyRun {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
```
Then run it from a shell, as follows:
```
$ spring run app.groovy
```
Note:
The first run of your application is slow, as dependencies are downloaded. Subsequent runs are much quicker.
Open `localhost:8080` in your favorite web browser. You should see the following output:
```
Hello World!
```
原文链接: https://docs.spring.io/spring-boot/docs/2.6.4/reference/html/getting-started.html#getting-started.installing
# Working a Getting Started guide with IntelliJ IDEA
This guide walks you through using IntelliJ IDEA to build one of the Getting Started guides.
## What you’ll build
You’ll pick a Spring guide and import it into IntelliJ IDEA. Then you can read the guide, work on the code, and run the project.
## What you’ll need
- About 15 minutes
- [IntelliJ IDEA](https://www.jetbrains.com/idea/download/)
- [JDK 6](http://www.oracle.com/technetwork/java/javase/downloads/index.html) or later
## Installing IntelliJ IDEA
If you don’t have IntelliJ IDEA (Ultimate Edition) installed yet, visit the link up above. From there, you can download a copy for your platform. To install it simply unpack the downloaded archive.
When you’re done, go ahead and launch IntelliJ IDEA.
## Importing a Getting Started guide
To import an existing project you need some code, so clone or copy one of the Getting Started guides, e.g. the [REST Service](https://spring.io/guides/gs/rest-service/) guide:
```
$ git clone https://github.com/spring-guides/gs-rest-service.gitCOPY
```
With IntelliJ IDEA up and running, click **Import Project** on the **Welcome Screen**, or **File | Open** on the main menu:
![spring_guide_welcome_import](./intellij_idea/spring_guide_welcome_import.png)
In the pop-up dialog make sure to select either [Maven](https://spring.io/guides/gs/maven)'s **pom.xml** or [Gradle](https://spring.io/guides/gs/gradle)'s **build.gradle** file under the **complete** folder:
![spring_guide_select_gradle_file](./intellij_idea/spring_guide_select_gradle_file.png)
IntelliJ IDEA will create a project with all the code from the guide ready to run.
## Creating a Project from Scratch
In case you’d like to start with an empty project and copy-and-paste your way through the guide, create a new **Maven** or **Gradle** project in the **Project Wizard**:
![spring_guide_new_project](./intellij_idea/spring_guide_new_project.png)
## See Also
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
## 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
# Spring Quickstart Guide
## What you'll build
You will build a classic “Hello World!” endpoint which any browser can connect to. You can even tell it your name, and it will respond in a more friendly way.
## What you’ll need
**An Integrated Developer Environment (IDE)**
Popular choices include [IntelliJ IDEA](https://www.jetbrains.com/idea/), [Spring Tools](https://spring.io/tools), [Visual Studio Code](https://code.visualstudio.com/docs/languages/java), or [Eclipse](https://www.eclipse.org/downloads/packages/), and many more.
**A Java™ Development Kit (JDK)**
We recommend [BellSoft Liberica JDK](https://bell-sw.com/) version 8 or version 11.
## Step 1: Start a new Spring Boot project
Use [start.spring.io](https://start.spring.io/) to create a “web” project. In the “Dependencies” dialog search for and add the “web” dependency as shown in the screenshot. Hit the “Generate” button, download the zip, and unpack it into a folder on your computer.
![quick-img-1-12bfde9c5c280b1940d85dee3d81772d](./quickstart_img/quick-img-1-12bfde9c5c280b1940d85dee3d81772d.png)
Projects created by [start.spring.io](https://start.spring.io/) contain [Spring Boot](https://spring.io/projects/spring-boot), a framework that makes Spring ready to work inside your app, but without much code or configuration required. Spring Boot is the quickest and most popular way to start Spring projects.
## Step 2: Add your code
Open up the project in your IDE and locate the `DemoApplication.java` file in the `src/main/java/com/example/demo` folder. Now change the contents of the file by adding the extra method and annotations shown in the code below. You can copy and paste the code or just type it.
```
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
}
```
*This is all the code required to create a simple “Hello World” web service in Spring Boot.*
The `hello()` method we’ve added is designed to take a String parameter called `name`, and then combine this parameter with the word `"Hello"` in the code. This means that if you set your name to `“Amy”` in the request, the response would be `“Hello Amy”`.
The `@RestController` annotation tells Spring that this code describes an endpoint that should be made available over the web. The `@GetMapping(“/hello”)` tells Spring to use our `hello()` method to answer requests that get sent to the `http://localhost:8080/hello` address. Finally, the `@RequestParam` is telling Spring to expect a `name` value in the request, but if it’s not there, it will use the word “World” by default.
## Step 3: Try it
Let’s build and run the program. Open a command line (or terminal) and navigate to the folder where you have the project files. We can build and run the application by issuing the following command:
**MacOS/Linux:**
```
./mvnw spring-boot:run
```
**Windows:**
```
mvnw spring-boot:run
```
You should see some output that looks very similar to this:
![quick-img2-ac5ae88c60ffaa062234a580f9f1abc3](./quickstart_img/quick-img2-ac5ae88c60ffaa062234a580f9f1abc3.png)
The last couple of lines here tell us that Spring has started. Spring Boot’s embedded Apache Tomcat server is acting as a webserver and is listening for requests on `localhost` port `8080`. Open your browser and in the address bar at the top enter http://localhost:8080/hello. You should get a nice friendly response like this:
![quick-img3-afa0a1fe446db8e3c8c7a8d9ca532d23](./quickstart_img/quick-img3-afa0a1fe446db8e3c8c7a8d9ca532d23.png)
原文链接: https://spring.io/quickstart
\ 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
# Spring Boot
\ No newline at end of file
此差异已折叠。
# Build Tool Plugins
Spring Boot provides build tool plugins for Maven and Gradle.
The plugins offer a variety of features, including the packaging of executable jars.
This section provides more details on both plugins as well as some help should you need to extend an unsupported build system.
If you are just getting started, you might want to read “[using.html](using.html#using.build-systems)” from the “[using.html](using.html#using)” section first.
## 1.1 Spring Boot Maven Plugin
The Spring Boot Maven Plugin provides Spring Boot support in Maven, letting you package executable jar or war archives and run an application “in-place”.
To use it, you must use Maven 3.2 (or later).
See the plugin’s documentation to learn more:
* Reference ([HTML](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/htmlsingle/) and [PDF](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/reference/pdf/spring-boot-maven-plugin-reference.pdf))
* [API](https://docs.spring.io/spring-boot/docs/2.6.4/maven-plugin/api/)
## 1.2. Spring Boot Gradle Plugin
The Spring Boot Gradle Plugin provides Spring Boot support in Gradle, letting you package executable jar or war archives, run Spring Boot applications, and use the dependency management provided by `spring-boot-dependencies`.
It requires Gradle 6.8, 6.9, or 7.x.
See the plugin’s documentation to learn more:
* Reference ([HTML](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/htmlsingle/) and [PDF](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/reference/pdf/spring-boot-gradle-plugin-reference.pdf))
* [API](https://docs.spring.io/spring-boot/docs/2.6.4/gradle-plugin/api/)
## 3. Spring Boot AntLib Module
The Spring Boot AntLib module provides basic Spring Boot support for Apache Ant.
You can use the module to create executable jars.
To use the module, you need to declare an additional `spring-boot` namespace in your `build.xml`, as shown in the following example:
```
<project xmlns:ivy="antlib:org.apache.ivy.ant"
xmlns:spring-boot="antlib:org.springframework.boot.ant"
name="myapp" default="build">
...
</project>
```
You need to remember to start Ant using the `-lib` option, as shown in the following example:
```
$ ant -lib <directory containing spring-boot-antlib-2.6.4.jar>
```
> The “Using Spring Boot” section includes a more complete example of [using Apache Ant with `spring-boot-antlib`](using.html#using.build-systems.ant).
### 3.1. Spring Boot Ant Tasks
Once the `spring-boot-antlib` namespace has been declared, the following additional tasks are available:
* [Using the “exejar” Task](#build-tool-plugins.antlib.tasks.exejar)
* [Using the “findmainclass” Task](#build-tool-plugins.antlib.findmainclass)
#### 3.1.1. Using the “exejar” Task
You can use the `exejar` task to create a Spring Boot executable jar.
The following attributes are supported by the task:
| Attribute | Description | Required |
|-------------|--------------------------------------|-------------------------------------------------------------------------|
| `destfile` | The destination jar file to create | Yes |
| `classes` |The root directory of Java class files| Yes |
|`start-class`| The main application class to run |No *(the default is the first class found that declares a `main` method)*|
The following nested elements can be used with the task:
| Element | Description |
|-----------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|`resources`|One or more [Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection) describing a set of [Resources](https://ant.apache.org/manual/Types/resources.html) that should be added to the content of the created jar file.|
| `lib` | One or more [Resource Collections](https://ant.apache.org/manual/Types/resources.html#collection) that should be added to the set of jar libraries that make up the runtime dependency classpath of the application. |
#### 3.1.2. Examples
This section shows two examples of Ant tasks.
Specify start-class
```
<spring-boot:exejar destfile="target/my-application.jar"
classes="target/classes" start-class="com.example.MyApplication">
<resources>
<fileset dir="src/main/resources" />
</resources>
<lib>
<fileset dir="lib" />
</lib>
</spring-boot:exejar>
```
Detect start-class
```
<exejar destfile="target/my-application.jar" classes="target/classes">
<lib>
<fileset dir="lib" />
</lib>
</exejar>
```
### 3.2. Using the “findmainclass” Task
The `findmainclass` task is used internally by `exejar` to locate a class declaring a `main`.
If necessary, you can also use this task directly in your build.
The following attributes are supported:
| Attribute | Description | Required |
|-------------|----------------------------------------------------|-------------------------------------------|
|`classesroot`| The root directory of Java class files | Yes *(unless `mainclass` is specified)* |
| `mainclass` |Can be used to short-circuit the `main` class search| No |
| `property` |The Ant property that should be set with the result |No *(result will be logged if unspecified)*|
#### 3.2.1. Examples
This section contains three examples of using `findmainclass`.
Find and log
```
<findmainclass classesroot="target/classes" />
```
Find and set
```
<findmainclass classesroot="target/classes" property="main-class" />
```
Override and set
```
<findmainclass mainclass="com.example.MainClass" property="main-class" />
```
## 4. Supporting Other Build Systems
If you want to use a build tool other than Maven, Gradle, or Ant, you likely need to develop your own plugin.
Executable jars need to follow a specific format and certain entries need to be written in an uncompressed form (see the “[executable jar format](executable-jar.html#appendix.executable-jar)” section in the appendix for details).
The Spring Boot Maven and Gradle plugins both make use of `spring-boot-loader-tools` to actually generate jars.
If you need to, you may use this library directly.
### 4.1. Repackaging Archives
To repackage an existing archive so that it becomes a self-contained executable archive, use `org.springframework.boot.loader.tools.Repackager`.
The `Repackager` class takes a single constructor argument that refers to an existing jar or war archive.
Use one of the two available `repackage()` methods to either replace the original file or write to a new destination.
Various settings can also be configured on the repackager before it is run.
### 4.2. Nested Libraries
When repackaging an archive, you can include references to dependency files by using the `org.springframework.boot.loader.tools.Libraries` interface.
We do not provide any concrete implementations of `Libraries` here as they are usually build-system-specific.
If your archive already includes libraries, you can use `Libraries.NONE`.
### 4.3. Finding a Main Class
If you do not use `Repackager.setMainClass()` to specify a main class, the repackager uses [ASM](https://asm.ow2.io/) to read class files and tries to find a suitable class with a `public static void main(String[] args)` method.
An exception is thrown if more than one candidate is found.
### 4.4. Example Repackage Implementation
The following example shows a typical repackage implementation:
```
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.springframework.boot.loader.tools.Library;
import org.springframework.boot.loader.tools.LibraryCallback;
import org.springframework.boot.loader.tools.LibraryScope;
import org.springframework.boot.loader.tools.Repackager;
public class MyBuildTool {
public void build() throws IOException {
File sourceJarFile = ...
Repackager repackager = new Repackager(sourceJarFile);
repackager.setBackupSource(false);
repackager.repackage(this::getLibraries);
}
private void getLibraries(LibraryCallback callback) throws IOException {
// Build system specific implementation, callback for each dependency
for (File nestedJar : getCompileScopeJars()) {
callback.library(new Library(nestedJar, LibraryScope.COMPILE));
}
// ...
}
private List<File> getCompileScopeJars() {
return ...
}
}
```
## 5. What to Read Next
If you are interested in how the build tool plugins work, you can look at the [`spring-boot-tools`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-tools) module on GitHub.
More technical details of the executable jar format are covered in [the appendix](executable-jar.html#appendix.executable-jar).
If you have specific build-related questions, see the “[how-to](howto.html#howto)” guides.
# Spring Boot CLI
The Spring Boot CLI is a command line tool that you can use if you want to quickly develop a Spring application.
It lets you run Groovy scripts, which means that you have a familiar Java-like syntax without so much boilerplate code.
You can also bootstrap a new project or write your own command for it.
## 1. Installing the CLI
The Spring Boot CLI (Command-Line Interface) can be installed manually by using SDKMAN! (the SDK Manager) or by using Homebrew or MacPorts if you are an OSX user.
See *[getting-started.html](getting-started.html#getting-started.installing.cli)* in the “Getting started” section for comprehensive installation instructions.
## 2. Using the CLI
Once you have installed the CLI, you can run it by typing `spring` and pressing Enter at the command line.
If you run `spring` without any arguments, a help screen is displayed, as follows:
```
$ spring
usage: spring [--help] [--version]
<command> [<args>]
Available commands are:
run [options] <files> [--] [args]
Run a spring groovy script
_... more command help is shown here_
```
You can type `spring help` to get more details about any of the supported commands, as shown in the following example:
```
$ spring help run
spring run - Run a spring groovy script
usage: spring run [options] <files> [--] [args]
Option Description
------ -----------
--autoconfigure [Boolean] Add autoconfigure compiler
transformations (default: true)
--classpath, -cp Additional classpath entries
--no-guess-dependencies Do not attempt to guess dependencies
--no-guess-imports Do not attempt to guess imports
-q, --quiet Quiet logging
-v, --verbose Verbose logging of dependency
resolution
--watch Watch the specified file for changes
```
The `version` command provides a quick way to check which version of Spring Boot you are using, as follows:
```
$ spring version
Spring CLI v2.6.4
```
### 2.1. Running Applications with the CLI
You can compile and run Groovy source code by using the `run` command.
The Spring Boot CLI is completely self-contained, so you do not need any external Groovy installation.
The following example shows a “hello world” web application written in Groovy:
hello.groovy
```
@RestController
class WebApplication {
@RequestMapping("/")
String home() {
"Hello World!"
}
}
```
To compile and run the application, type the following command:
```
$ spring run hello.groovy
```
To pass command-line arguments to the application, use `--` to separate the commands from the “spring” command arguments, as shown in the following example:
```
$ spring run hello.groovy -- --server.port=9000
```
To set JVM command line arguments, you can use the `JAVA_OPTS` environment variable, as shown in the following example:
```
$ JAVA_OPTS=-Xmx1024m spring run hello.groovy
```
| |When setting `JAVA_OPTS` on Microsoft Windows, make sure to quote the entire instruction, such as `set "JAVA_OPTS=-Xms256m -Xmx2048m"`.<br/>Doing so ensures the values are properly passed to the process.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.1. Deduced “grab” Dependencies
Standard Groovy includes a `@Grab` annotation, which lets you declare dependencies on third-party libraries.
This useful technique lets Groovy download jars in the same way as Maven or Gradle would but without requiring you to use a build tool.
Spring Boot extends this technique further and tries to deduce which libraries to “grab” based on your code.
For example, since the `WebApplication` code shown previously uses `@RestController` annotations, Spring Boot grabs "Tomcat" and "Spring MVC".
The following items are used as “grab hints”:
| Items | Grabs |
|----------------------------------------------------------|------------------------------|
|`JdbcTemplate`, `NamedParameterJdbcTemplate`, `DataSource`| JDBC Application. |
| `@EnableJms` | JMS Application. |
| `@EnableCaching` | Caching abstraction. |
| `@Test` | JUnit. |
| `@EnableRabbit` | RabbitMQ. |
| extends `Specification` | Spock test. |
| `@EnableBatchProcessing` | Spring Batch. |
| `@MessageEndpoint` `@EnableIntegration` | Spring Integration. |
| `@Controller` `@RestController` `@EnableWebMvc` |Spring MVC + Embedded Tomcat. |
| `@EnableWebSecurity` | Spring Security. |
| `@EnableTransactionManagement` |Spring Transaction Management.|
| |See subclasses of [`CompilerAutoConfiguration`](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli/compiler/CompilerAutoConfiguration.java) in the Spring Boot CLI source code to understand exactly how customizations are applied.|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.2. Deduced “grab” Coordinates
Spring Boot extends Groovy’s standard `@Grab` support by letting you specify a dependency without a group or version (for example, `@Grab('freemarker')`).
Doing so consults Spring Boot’s default dependency metadata to deduce the artifact’s group and version.
| |The default metadata is tied to the version of the CLI that you use.<br/>It changes only when you move to a new version of the CLI, putting you in control of when the versions of your dependencies may change.<br/>A table showing the dependencies and their versions that are included in the default metadata can be found in the [appendix](dependency-versions.html#appendix.dependency-versions).|
|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.3. Default Import Statements
To help reduce the size of your Groovy code, several `import` statements are automatically included.
Notice how the preceding example refers to `@Component`, `@RestController`, and `@RequestMapping` without needing to use fully-qualified names or `import` statements.
| |Many Spring annotations work without using `import` statements.<br/>Try running your application to see what fails before adding imports.|
|---|-----------------------------------------------------------------------------------------------------------------------------------------|
#### 2.1.4. Automatic Main Method
Unlike the equivalent Java application, you do not need to include a `public static void main(String[] args)` method with your `Groovy` scripts.
A `SpringApplication` is automatically created, with your compiled code acting as the `source`.
#### 2.1.5. Custom Dependency Management
By default, the CLI uses the dependency management declared in `spring-boot-dependencies` when resolving `@Grab` dependencies.
Additional dependency management, which overrides the default dependency management, can be configured by using the `@DependencyManagementBom` annotation.
The annotation’s value should specify the coordinates (`groupId:artifactId:version`) of one or more Maven BOMs.
For example, consider the following declaration:
```
@DependencyManagementBom("com.example.custom-bom:1.0.0")
```
The preceding declaration picks up `custom-bom-1.0.0.pom` in a Maven repository under `com/example/custom-versions/1.0.0/`.
When you specify multiple BOMs, they are applied in the order in which you declare them, as shown in the following example:
```
@DependencyManagementBom([
"com.example.custom-bom:1.0.0",
"com.example.another-bom:1.0.0"])
```
The preceding example indicates that the dependency management in `another-bom` overrides the dependency management in `custom-bom`.
You can use `@DependencyManagementBom` anywhere that you can use `@Grab`.
However, to ensure consistent ordering of the dependency management, you can use `@DependencyManagementBom` at most once in your application.
### 2.2. Applications with Multiple Source Files
You can use “shell globbing” with all commands that accept file input.
Doing so lets you use multiple files from a single directory, as shown in the following example:
```
$ spring run *.groovy
```
### 2.3. Packaging Your Application
You can use the `jar` command to package your application into a self-contained executable jar file, as shown in the following example:
```
$ spring jar my-app.jar *.groovy
```
The resulting jar contains the classes produced by compiling the application and all of the application’s dependencies so that it can then be run by using `java -jar`.
The jar file also contains entries from the application’s classpath.
You can add and remove explicit paths to the jar by using `--include` and `--exclude`.
Both are comma-separated, and both accept prefixes, in the form of “+” and “-”, to signify that they should be removed from the defaults.
The default includes are as follows:
```
public/**, resources/**, static/**, templates/**, META-INF/**, *
```
The default excludes are as follows:
```
.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy
```
Type `spring help jar` on the command line for more information.
### 2.4. Initialize a New Project
The `init` command lets you create a new project by using [start.spring.io](https://start.spring.io) without leaving the shell, as shown in the following example:
```
$ spring init --dependencies=web,data-jpa my-project
Using service at https://start.spring.io
Project extracted to '/Users/developer/example/my-project'
```
The preceding example creates a `my-project` directory with a Maven-based project that uses `spring-boot-starter-web` and `spring-boot-starter-data-jpa`.
You can list the capabilities of the service by using the `--list` flag, as shown in the following example:
```
$ spring init --list
=======================================
Capabilities of https://start.spring.io
=======================================
Available dependencies:
-----------------------
actuator - Actuator: Production ready features to help you monitor and manage your application
...
web - Web: Support for full-stack web development, including Tomcat and spring-webmvc
websocket - Websocket: Support for WebSocket development
ws - WS: Support for Spring Web Services
Available project types:
------------------------
gradle-build - Gradle Config [format:build, build:gradle]
gradle-project - Gradle Project [format:project, build:gradle]
maven-build - Maven POM [format:build, build:maven]
maven-project - Maven Project [format:project, build:maven] (default)
...
```
The `init` command supports many options.
See the `help` output for more details.
For instance, the following command creates a Gradle project that uses Java 8 and `war` packaging:
```
$ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip
Using service at https://start.spring.io
Content saved to 'sample-app.zip'
```
### 2.5. Using the Embedded Shell
Spring Boot includes command-line completion scripts for the BASH and zsh shells.
If you do not use either of these shells (perhaps you are a Windows user), you can use the `shell` command to launch an integrated shell, as shown in the following example:
```
$ spring shell
Spring Boot (v2.6.4)
Hit TAB to complete. Type \'help' and hit RETURN for help, and \'exit' to quit.
```
From inside the embedded shell, you can run other commands directly:
```
$ version
Spring CLI v2.6.4
```
The embedded shell supports ANSI color output as well as `tab` completion.
If you need to run a native command, you can use the `!` prefix.
To exit the embedded shell, press `ctrl-c`.
### 2.6. Adding Extensions to the CLI
You can add extensions to the CLI by using the `install` command.
The command takes one or more sets of artifact coordinates in the format `group:artifact:version`, as shown in the following example:
```
$ spring install com.example:spring-boot-cli-extension:1.0.0.RELEASE
```
In addition to installing the artifacts identified by the coordinates you supply, all of the artifacts' dependencies are also installed.
To uninstall a dependency, use the `uninstall` command.
As with the `install` command, it takes one or more sets of artifact coordinates in the format of `group:artifact:version`, as shown in the following example:
```
$ spring uninstall com.example:spring-boot-cli-extension:1.0.0.RELEASE
```
It uninstalls the artifacts identified by the coordinates you supply and their dependencies.
To uninstall all additional dependencies, you can use the `--all` option, as shown in the following example:
```
$ spring uninstall --all
```
## 3. Developing Applications with the Groovy Beans DSL
Spring Framework 4.0 has native support for a `beans{}` “DSL” (borrowed from [Grails](https://grails.org/)), and you can embed bean definitions in your Groovy application scripts by using the same format.
This is sometimes a good way to include external features like middleware declarations, as shown in the following example:
```
@Configuration(proxyBeanMethods = false)
class Application implements CommandLineRunner {
@Autowired
SharedService service
@Override
void run(String... args) {
println service.message
}
}
import my.company.SharedService
beans {
service(SharedService) {
message = "Hello World"
}
}
```
You can mix class declarations with `beans{}` in the same file as long as they stay at the top level, or, if you prefer, you can put the beans DSL in a separate file.
## 4. Configuring the CLI with settings.xml
The Spring Boot CLI uses Maven Resolver, Maven’s dependency resolution engine, to resolve dependencies.
The CLI makes use of the Maven configuration found in `~/.m2/settings.xml` to configure Maven Resolver.
The following configuration settings are honored by the CLI:
* Offline
* Mirrors
* Servers
* Proxies
* Profiles
* Activation
* Repositories
* Active profiles
See [Maven’s settings documentation](https://maven.apache.org/settings.html) for further information.
## 5. What to Read Next
There are some [sample groovy scripts](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/samples) available from the GitHub repository that you can use to try out the Spring Boot CLI.
There is also extensive Javadoc throughout the [source code](https://github.com/spring-projects/spring-boot/tree/v2.6.4/spring-boot-project/spring-boot-cli/src/main/java/org/springframework/boot/cli).
If you find that you reach the limit of the CLI tool, you probably want to look at converting your application to a full Gradle or Maven built “Groovy project”.
The next section covers Spring Boot’s "[Build tool plugins](build-tool-plugins.html#build-tool-plugins)", which you can use with Gradle or Maven.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Getting Help
If you have trouble with Spring Boot, we would like to help.
* Try the [How-to documents](howto.html#howto).
They provide solutions to the most common questions.
* Learn the Spring basics.
Spring Boot builds on many other Spring projects.
Check the [spring.io](https://spring.io) web-site for a wealth of reference documentation.
If you are starting out with Spring, try one of the [guides](https://spring.io/guides).
* Ask a question.
We monitor [stackoverflow.com](https://stackoverflow.com) for questions tagged with [`spring-boot`](https://stackoverflow.com/tags/spring-boot).
* Report bugs with Spring Boot at [github.com/spring-projects/spring-boot/issues](https://github.com/spring-projects/spring-boot/issues).
Note:
All of Spring Boot is open source, including the documentation. If you find problems with the docs or if you want to improve them, please [get involved](https://github.com/spring-projects/spring-boot/tree/v2.6.4).
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Legal
Copyright © 2012-2022
Copies of this document may be made for your own use and for distribution to
others, provided that you do not charge any fee for such copies and further
provided that each copy contains this Copyright Notice, whether distributed in
print or electronically.
此差异已折叠。
# Upgrading Spring Boot
Instructions for how to upgrade from earlier versions of Spring Boot are provided on the project [wiki](https://github.com/spring-projects/spring-boot/wiki).
Follow the links in the [release notes](https://github.com/spring-projects/spring-boot/wiki#release-notes) section to find the version that you want to upgrade to.
Upgrading instructions are always the first item in the release notes.
If you are more than one release behind, please make sure that you also review the release notes of the versions that you jumped.
## 1. Upgrading from 1.x
If you are upgrading from the `1.x` release of Spring Boot, check the [“migration guide” on the project wiki](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide) that provides detailed upgrade instructions.
Check also the [“release notes”](https://github.com/spring-projects/spring-boot/wiki) for a list of “new and noteworthy” features for each release.
## 2. Upgrading to a new feature release
When upgrading to a new feature release, some properties may have been renamed or removed.
Spring Boot provides a way to analyze your application’s environment and print diagnostics at startup, but also temporarily migrate properties at runtime for you.
To enable that feature, add the following dependency to your project:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-properties-migrator</artifactId>
<scope>runtime</scope>
</dependency>
```
| |Properties that are added late to the environment, such as when using `@PropertySource`, will not be taken into account.|
|---|------------------------------------------------------------------------------------------------------------------------|
| |Once you finish the migration, please make sure to remove this module from your project’s dependencies.|
|---|-------------------------------------------------------------------------------------------------------|
## 3. Upgrading the Spring Boot CLI
To upgrade an existing CLI installation, use the appropriate package manager command (for example, `brew upgrade`).
If you manually installed the CLI, follow the [standard instructions](getting-started.html#getting-started.installing.cli.manual-installation), remembering to update your `PATH` environment variable to remove any older references.
## 4. What to Read Next
Once you’ve decided to upgrade your application, you can find detailed information regarding specific features in the rest of the document.
Spring Boot’s documentation is specific to that version, so any information that you find in here will contain the most up-to-date changes that are in that version.
此差异已折叠。
此差异已折叠。
# Spring Cloud Data Flow
\ No newline at end of file
# Spring Cloud
\ No newline at end of file
# Spring Cloud Documentation
This section provides a brief overview of Spring Cloud reference documentation. It serves
as a map for the rest of the document.
## [](#documentation-about)[1. About the Documentation](#documentation-about)
The Spring Cloud reference guide is available as
* [Multi-page HTML](https://docs.spring.io/spring-cloud/docs/2021.0.1/reference/html)
* [Single-page HTML](https://docs.spring.io/spring-cloud/docs/2021.0.1/reference/htmlsingle)
* [PDF](https://docs.spring.io/spring-cloud/docs/2021.0.1/reference/pdf/spring-cloud.pdf)
Copies of this document may be made for your own use and for distribution to others,
provided that you do not charge any fee for such copies and further provided that each
copy contains this Copyright Notice, whether distributed in print or electronically.
## [](#documentation-getting-help)[2. Getting Help](#documentation-getting-help)
If you have trouble with Spring Cloud, we would like to help.
* Learn the Spring Cloud basics. If you are
starting out with Spring Cloud, try one of the [guides](https://spring.io/guides).
* Ask a question. We monitor [stackoverflow.com](https://stackoverflow.com) for questions
tagged with [`spring-cloud`](https://stackoverflow.com/tags/spring-cloud).
* Chat with us at [Spring Cloud Gitter](https://gitter.im/spring-cloud/spring-cloud)
| |All of Spring Cloud is open source, including the documentation. If you find<br/>problems with the docs or if you want to improve them, please get involved.|
|---|------------------------------------------------------------------------------------------------------------------------------------------------------------|
if (window.parent == window) {(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1\*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', 'UA-2728886-23', 'auto', {'siteSpeedSampleRate': 100});ga('send', 'pageview');}
\ No newline at end of file
# Legal
2021.0.1
Copyright © 2012-2020
Copies of this document may be made for your own use and for distribution to
others, provided that you do not charge any fee for such copies and further
provided that each copy contains this Copyright Notice, whether distributed in
print or electronically.
if (window.parent == window) {(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1\*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','//www.google-analytics.com/analytics.js','ga');ga('create', 'UA-2728886-23', 'auto', {'siteSpeedSampleRate': 100});ga('send', 'pageview');}
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
# Spring Data
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册