1.Springboot快速开始
系列文章目录:SpringBoot文档API翻译
1 启动一个新的 Spring Boot 项目
用 start.spring.io创建一个WEB项目。在“Dependencies”对话框中搜索并添加“web”依赖项,如下截图所示。点击“Generate”按钮,下载 zip,然后将其解压到计算机上的文件夹中。
创建的项目 start.spring.io 包含 SpringBoot ,一个使 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);
}
}
hello()我们添加的方法接收一个 String 类型参数name,然后将此参数与"Hello"单词组合。这意味着如果您在请求中将您的姓名设置为“Amy”,则响应将为“Hello Amy”。
该@RestController注解告诉Spring,这是一个restful接口。该@GetMapping(“/hello”)告诉Spring使用我们的hello()方法来响应http://localhost:8080/hello的请求。最后,@RequestParam告诉 Springname在请求中期望一个值,但如果它不存在,它将默认使用单词“World”。
3 运行
让我们构建并运行程序。 打开命令行(或终端)并导航到项目文件所在的文件夹。 我们可以通过发出以下命令来构建和运行应用程序:
MacOS/Linux:
./mvnw spring-boot:run
Windows:
mvnw spring-boot:run
您应该会看到一些与此非常相似的输出:
这里的最后几行告诉我们 Spring 已经开始。 Spring Boot 的嵌入式 Apache Tomcat 服务器充当网络服务器并侦听 localhost 端口上的 请求 8080 。 打开浏览器并在顶部的地址栏中输入 http://localhost:8080/你好 . 你应该得到这样一个友好的回应:
原创不易,如果您喜欢请支持一下我的创作。
支付宝 | 微信 |
---|---|