本文记录对于SpringBoot的第一次接触。
一、环境要求SpringBoot 2.5.5
jdk 1.8+
maven 3.3+
- 给maven的settings.xml配置文件的profiles标签添加,让Maven使用jdk1.8进行编译,就可以避免项目
开发中出现的一些问题。
jdk-1.8 true 1.8 1.8 1.8 1.8
- 添加阿里云镜像,加速jar包的下载速度
三、创建Maven项目nexus-aliyun * Nexus aliyun https://maven.aliyun.com/repository/central
- 配置Maven配置文件(setting.xml)路径和本地仓库路径
- 修改pom.xml文件,导入父工程和SpringBoot的Web场景依赖。
SpringBoot提供了一系列的starters(启动器),用于自动的依赖管理与版本控制。比如要用web
功能,则导入web启动器,Web应用中需要包含的jar包,以及每个jar包的版本,SpringBoot都可
以帮我们控制好。
四、添加控制器org.springframework.boot spring-boot-starter-parent 2.5.5 org.springframework.boot spring-boot-starter-web
文件目录:
其中Greeting为实体类:
package com.example.demo;
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;
}
}
控制器内容:
package com.example.demo;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
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 greetingGet(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
@PostMapping("/greeting")
public Greeting greetingPost(@RequestParam(value = "user", defaultValue = "default") String user,@RequestParam(value = "pwd", defaultValue = "default") String pwd) {
return new Greeting(3, "Hello SpringBoot!");
}
}
五、启动SpringBoot应用
注意: SpringBoot的主程序类不能直接放到java包下
主程序类:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
六、部署
- 在pom.xml文件中添加 spring-boot-maven-plugin 插件
org.springframework.boot spring-boot-maven-plugin
- 把项目打成jar包或war包
- 通过运行java -jar命令即可开启web服务
- 运行结果
响应Get请求
响应Post请求
SpringBoot相比于SpringMVC来说要简便很多,这是因为SpringBoot自动为项目添加了许多maven依赖,避免了繁琐的人工添加.。



