# Spring 快速入门指南

# 您将构建什么

您将构建一个经典的“Hello World!” 任何浏览器都可以连接的终端。你甚至可以告诉它你的名字,它会以更友好的方式回应。

# 你需要什么

集成开发人员环境 (IDE)

热门选择包括IntelliJ IDEA (opens new window),Spring Tools (opens new window),Visual Studio Code (opens new window)Eclipse (opens new window)等等。

Java™ 开发工具包 (JDK)

我们推荐BellSoft Liberica JDK (opens new window)版本 8 或版本 11。

# 第一步:开始一个新的 Spring Boot 项目

通过start.spring.io (opens new window)创建一个“web”项目。在“依赖项”对话框中搜索并添加“web”依赖项,如屏幕截图所示。点击“生成”按钮,下载 zip,然后将其解压缩到计算机上的文件夹中。

quick-img-1-12bfde9c5c280b1940d85dee3d81772d

通过start.spring.io (opens new window)创建的项目包含Spring Boot (opens new window),Spring Boot是一个不需要太多代码或配置,就可以使Spring在您的应用程序中正常工作的框架,Spring Boot 是使用 Spring 项目的最快、最流行的方式。

# 第 2 步:添加您的代码

在 IDE 中打开项目并在文件夹DemoApplication.java中找到该文件src/main/java/com/example/demo。现在通过添加下面代码中显示的额外方法和注解来更改文件的内容。您可以复制并粘贴代码或直接输入。


              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);
                  }
                
              }
            

这是在Spring Boot中创建一个简单的“Hello World”Web服务所需的所有代码。

hello()方法,我们设计成接收一个字符串参数name,然后将该参数与"Hello"连接起来。如果您请求时将name设置为“Amy”,服务将会返回“Hello Amy”.

@RestController注解告诉 Spring 这段代码描述了一个应该在 web 上可用的端点。 @GetMapping(“/hello”)告诉 Spring 使用我们的方法hello()来响应发送到该http://localhost:8080/hello地址的请求。 @RequestParam告诉 Spring期望请求中包含name参数,但如果它不存在,将使用默认值“World”。

# 第 3 步:尝试一下

让我们构建并运行程序。打开命令行(或终端)并进入到项目所在文件夹。可以通过以下命令来构建和运行应用程序:

MacOS/Linux:

./mvnw spring-boot:run

Windows:

mvnw spring-boot:run

您应该会看到一些与此非常相似的输出:

quick-img2-ac5ae88c60ffaa062234a580f9f1abc3

最后的几行日志显示Spring已经启动了。Spring Boot 的嵌入式 Apache Tomcat 服务器充当 Web 服务器,并正在监听localhost8080端口请求。打开浏览器,在地址栏中输入http://localhost:8080/hello (opens new window). 你应该得到一个很好的友好回应,如下所示:

quick-img3-afa0a1fe446db8e3c8c7a8d9ca532d23

原文链接: https://spring.io/quickstart