Spring Boot quick start

前言

Spring是一个Java框架,可以用于MicroservicesReactiveCloudWeb AppServerlessEventDrivenBatch等,具有应用广泛、高效、灵活、高速、安全、丰富的社区支持等特性

官网:https://spring.io

当前文章的主要内容是启动一个Spring Boot项目,它具有一个/hello接口,这个接口支持传递name参数,如果没有读取到name参数,则使用默认值的World,并基于name参数返回一个字符串

1、下载demo

在官网http://start.spring.io生成一个demo。

该页面的Project选择MavenSpring Boot选择3.2.3,在Add Dependence中搜索web并选择Spring Web,最后点击下方的Generate按钮就会下在一个demo.zip

spring boot generate

解压后得到的文件结构如下:

demo

2、新增hello函数及接口

这里使用VS Code打开demo,并修改源码如下:

DemoApplication.java

DemoApplication.java

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与其拼接,返回拼接之后的字符串。举个例子如果传入的name=Jack,那么最终返回的是一个"Hello Jack"字符串

类名之上@RestController声明意味着当前代码是一个支持web后端代码

方法声明之前@GetMapping("/hello")表示我们的hello()方法是用于响应发送到"http://localhost:8080/hello"地址的请求。

hell0()函数签名中,位于name之前的@RequestParam(value = "name", defaultValue = "World")意味着希望从请求中读取name字段,若未读取到该字段则使用默认的字符串"World"传递给当前函数的参数name

在我们编辑代码的同时会自动导入所需要的包,如顶部的import org.springframework.web.bind.annotation.RestController;等。

3、启动并调试该接口

点击VS Code右上角的三角形▶️按钮即可运行当前程序。运行成功后会在控制台的terminal显示以下内容:

spring boot run

如果需要停止运行,点击以下Disconnect按钮即可:

spring disconnect

在程序运行过程中,我们在浏览器访问"http://localhost:8080/hello",将会看到以下内容:

http://localhost:8080/hello

这表示我们访问本地服务器的/hello接口,并且没有带任何参数。由于我们的hello()方法在没有读取到name参数时会使用默认的"World"字符串当作默认参数,所以最终我们看到浏览器显示了拼接Hello之后的字符串"Hello World"

我们再尝试带上指定的name参数Hsiao:再次访问"http://localhost:8080/hello?name=Hsiao",此时浏览器将显示:

“http://localhost:8080/hello?name=Hsiao”