Spring Boot for Beginners (2026 Edition)
Build a Spring Boot 3 application from zero: starter dependencies, auto-configuration, application.yml, RESTful APIs, validation, unit testing and jar packaging with full source code.
Why Spring Boot
Spring Boot is the de facto Java backend framework. It auto-configures the Spring container, embeds Tomcat so a jar runs as a web server, provides starter dependency bundles, and includes production features like metrics and health checks (actuator).
# 用 Spring Initializr 生成项目(或通过 IDEA 向导)
curl https://start.spring.io/starter.zip \
-d type=maven-project -d language=java \
-d bootVersion=3.5.0 -d baseDir=demo \
-d dependencies=web,validation,lombok \
-o demo.zip
# 运行
./mvnw spring-boot:run
java -jar target/demo-0.0.1-SNAPSHOT.jar
Project Structure and pom.xml
demo/
├── pom.xml
└── src/main/
├── java/com/example/demo/
│ ├── DemoApplication.java // 启动类
│ ├── controller/
│ ├── service/
│ ├── repository/
│ └── entity/
└── resources/
└── application.yml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
Auto-Configuration Principles
@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan. Spring Boot scans the classpath and, when a class is present (e.g., Tomcat, Jackson), creates beans that match — @ConditionalOnClass / @ConditionalOnMissingBean annotations decide whether each auto-configuration applies. You can always override any bean by defining your own.
Writing a RESTful API
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
// 构造注入(推荐,final + 构造器)
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.getById(id);
}
@PostMapping
public User create(@Valid @RequestBody UserDto dto) {
return userService.create(dto);
}
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody UserDto dto) {
return userService.update(id, dto);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.delete(id);
}
}
// DTO 与校验
public record UserDto(
@NotBlank String name,
@Email String email,
@Min(0) Integer age) {}
Return objects directly — Spring serializes them to JSON via Jackson. Add @Valid to trigger Bean Validation. A unified exception handler with @RestControllerAdvice converts validation exceptions into clean error responses.
Configuration Files
# application.yml
server:
port: 8080
spring:
application:
name: demo
datasource:
url: jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
username: root
password: ${DB_PASSWORD:root} # 环境变量覆盖
jpa:
hibernate:
ddl-auto: update
logging:
level:
com.example.demo: DEBUG
- Load order: application.yml -> application-{profile}.yml, activate profiles with spring.profiles.active.
- Externalize configs at runtime with command line args or env vars: java -jar app.jar --server.port=9000.
Unit Testing and Packaging
@SpringBootTest
class UserControllerTest {
@Autowired
private MockMvc mockMvc; // 模拟 HTTP 调用
@Test
void shouldGetUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}
./mvnw clean package # 生成可执行 jar
target/demo-0.0.1-SNAPSHOT.jar
nohup java -Xms512m -Xmx512m -jar demo.jar > app.log 2>&1 &
# 生产建议加 -XX:+UseG1GC / -XX:MaxRAMPercentage=75
The fat jar embeds Tomcat — no external server needed. For Docker, copy the jar into an eclipse-temurin:21-jre image and set the entrypoint.
为什么用 Spring Boot
Spring Boot 是 Java 后端的事实标准框架:自动装配 Spring 容器、内嵌 Tomcat 让一个 jar 就能跑起 Web 服务、用 starter 简化依赖管理、自带监控与健康检查(actuator)等生产级特性。
# 用 Spring Initializr 生成项目(或通过 IDEA 向导)
curl https://start.spring.io/starter.zip \
-d type=maven-project -d language=java \
-d bootVersion=3.5.0 -d baseDir=demo \
-d dependencies=web,validation,lombok \
-o demo.zip
# 运行
./mvnw spring-boot:run
java -jar target/demo-0.0.1-SNAPSHOT.jar
项目结构与 pom.xml
demo/
├── pom.xml
└── src/main/
├── java/com/example/demo/
│ ├── DemoApplication.java // 启动类
│ ├── controller/
│ ├── service/
│ ├── repository/
│ └── entity/
└── resources/
└── application.yml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
自动配置原理
@SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan。Spring Boot 扫描 classpath,发现某个类存在(如 Tomcat、Jackson)就创建相应的 Bean,@ConditionalOnClass / @ConditionalOnMissingBean 决定自动配置是否生效。自定义 Bean 优先级高于自动配置,随时可覆盖。
编写 RESTful 接口
@RestController
@RequestMapping("/api/users")
public class UserController {
private final UserService userService;
// 构造注入(推荐,final + 构造器)
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.getById(id);
}
@PostMapping
public User create(@Valid @RequestBody UserDto dto) {
return userService.create(dto);
}
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody UserDto dto) {
return userService.update(id, dto);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.delete(id);
}
}
// DTO 与校验
public record UserDto(
@NotBlank String name,
@Email String email,
@Min(0) Integer age) {}
直接返回对象即可,Spring 会用 Jackson 序列化为 JSON;加 @Valid 触发参数校验;配合 @RestControllerAdvice 统一异常处理,把校验异常转成规范的错误响应。
配置文件
# application.yml
server:
port: 8080
spring:
application:
name: demo
datasource:
url: jdbc:mysql://localhost:3306/demo?useSSL=false&serverTimezone=UTC
username: root
password: ${DB_PASSWORD:root} # 环境变量覆盖
jpa:
hibernate:
ddl-auto: update
logging:
level:
com.example.demo: DEBUG
- 加载顺序:application.yml → application-{profile}.yml,用 spring.profiles.active 激活环境。
- 运行期用命令行参数或环境变量覆盖:java -jar app.jar --server.port=9000。
单元测试与打包部署
@SpringBootTest
class UserControllerTest {
@Autowired
private MockMvc mockMvc; // 模拟 HTTP 调用
@Test
void shouldGetUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}
./mvnw clean package # 生成可执行 jar
target/demo-0.0.1-SNAPSHOT.jar
nohup java -Xms512m -Xmx512m -jar demo.jar > app.log 2>&1 &
# 生产建议加 -XX:+UseG1GC / -XX:MaxRAMPercentage=75
fat jar 内嵌 Tomcat,无需额外服务器。Docker 化时把 jar 拷进 eclipse-temurin:21-jre 镜像并设置 entrypoint 即可。