SpringBoot入门教程 - 从零开始学习Spring Boot框架完整指南
SpringBoot入门教程 - 从零开始学习Spring Boot框架完整指南
Spring Boot是Spring框架的扩展,旨在简化Spring应用的初始搭建以及开发过程。本教程将带你从零开始,系统学习Spring Boot的核心概念和实际应用,通过详细的代码示例和实战项目,让你快速掌握Spring Boot开发技能。
📚 目录
- Spring Boot简介
- 环境搭建
- 第一个Spring Boot应用
- Spring Boot核心概念
- 配置文件管理
- Web开发
- 数据访问
- Spring Boot Starter
- 自动配置原理
- 测试
- 部署与运维
- 实战项目
- 常见问题解答
- 学习资源推荐
1. Spring Boot简介
1.1 什么是Spring Boot
Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。Spring Boot基于Spring框架,通过"约定优于配置"的理念,让开发者能够快速创建独立运行、生产级别的Spring应用。
1.2 Spring Boot的核心特性
1.2.1 自动配置(Auto Configuration)
- 零配置启动:Spring Boot能够根据类路径中的jar包自动配置应用
- 智能默认值:提供合理的默认配置,减少手动配置
- 条件化配置:根据环境自动启用或禁用配置
1.2.2 起步依赖(Starter Dependencies)
- 依赖管理:通过starter简化依赖配置
- 版本兼容:自动管理依赖版本,避免冲突
- 功能模块化:按需引入功能模块
1.2.3 内嵌服务器(Embedded Server)
- 无需部署:应用可直接运行,无需外部服务器
- 支持多种服务器:Tomcat、Jetty、Undertow
- 简化部署:打包成jar即可运行
1.2.4 生产就绪(Production Ready)
- 监控端点:Actuator提供健康检查、指标监控
- 外部化配置:支持多种配置方式
- 日志管理:集成Logback、Log4j2
1.3 Spring Boot vs Spring Framework
| 特性 | Spring Framework | Spring Boot |
|---|---|---|
| 配置方式 | XML或Java配置 | 自动配置 |
| 依赖管理 | 手动管理 | Starter自动管理 |
| 服务器 | 需要外部服务器 | 内嵌服务器 |
| 开发效率 | 较慢 | 快速 |
| 学习曲线 | 较陡 | 平缓 |
| 适用场景 | 复杂企业应用 | 快速开发、微服务 |
1.4 Spring Boot版本历史
- Spring Boot 1.0 (2014年) - 首个正式版本
- Spring Boot 2.0 (2018年) - 重大更新,支持Java 9+
- Spring Boot 2.7 (2022年) - 最后一个2.x版本
- Spring Boot 3.0 (2022年) - 支持Java 17+,基于Spring 6
- Spring Boot 3.1+ (2023年) - 持续更新
1.5 Spring Boot应用场景
- Web应用开发:RESTful API、Web应用
- 微服务架构:Spring Cloud微服务
- 批处理应用:Spring Batch
- 消息驱动应用:Spring Integration
- 快速原型开发:MVP、Demo项目
2. 环境搭建
2.1 前置要求
Java版本要求
- Spring Boot 2.x:需要Java 8或更高版本
- Spring Boot 3.x:需要Java 17或更高版本(推荐Java 17 LTS)
开发工具
- IDE:IntelliJ IDEA(推荐)、Eclipse、VS Code
- 构建工具:Maven 3.3+ 或 Gradle 6.x+
- 版本控制:Git
2.2 安装Java
检查Java版本
java -version如果未安装或版本不符合要求,请参考Java入门教程安装JDK。
2.3 安装Maven
Windows系统
- 下载Maven:https://maven.apache.org/download.cgi
- 解压到目录(如:
C:\Program Files\Apache\maven) - 配置环境变量:
MAVEN_HOME=C:\Program Files\Apache\mavenPath添加%MAVEN_HOME%\bin
- 验证安装:
mvn -versionmacOS系统
brew install mavenLinux系统
sudo apt install maven # Ubuntu/Debian
sudo yum install maven # CentOS/RHEL2.4 安装IDE(IntelliJ IDEA推荐)
- 下载IntelliJ IDEA:https://www.jetbrains.com/idea/
- 安装并启动
- 安装Spring Boot插件(通常已内置)
2.5 验证环境
创建测试项目验证环境是否正确配置。
3. 第一个Spring Boot应用
3.1 使用Spring Initializr创建项目
方式1:通过网站创建(推荐)
- 访问:https://start.spring.io/
- 选择配置:
- Project:Maven Project
- Language:Java
- Spring Boot:3.1.5(或最新稳定版)
- Project Metadata:
- Group:com.example
- Artifact:demo
- Name:demo
- Package name:com.example.demo
- Packaging:Jar
- Java:17
- 添加依赖:
- Spring Web
- Spring Boot DevTools(开发工具)
- 点击"Generate"下载项目
方式2:使用IDE创建
IntelliJ IDEA:
- File → New → Project
- 选择Spring Initializr
- 配置项目信息
- 选择依赖
- 完成创建
Eclipse:
- File → New → Spring Starter Project
- 配置项目信息
- 选择依赖
- 完成创建
方式3:使用命令行
curl https://start.spring.io/starter.zip \
-d type=maven-project \
-d language=java \
-d bootVersion=3.1.5 \
-d baseDir=myapp \
-d groupId=com.example \
-d artifactId=myapp \
-d name=myapp \
-d packageName=com.example.myapp \
-d packaging=jar \
-d javaVersion=17 \
-d dependencies=web,devtools \
-o myapp.zip
unzip myapp.zip
cd myapp3.2 项目结构解析
创建后的项目结构:
myapp/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── myapp/
│ │ │ └── MyappApplication.java # 主启动类
│ │ └── resources/
│ │ ├── application.properties # 配置文件
│ │ └── static/ # 静态资源
│ │ └── templates/ # 模板文件
│ └── test/
│ └── java/
│ └── com/
│ └── example/
│ └── myapp/
│ └── MyappApplicationTests.java # 测试类
├── pom.xml # Maven配置文件
└── README.md3.3 主启动类解析
package com.example.myapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyappApplication {
public static void main(String[] args) {
SpringApplication.run(MyappApplication.class, args);
}
}关键注解说明:
@SpringBootApplication:组合注解,包含:@SpringBootConfiguration:标识为配置类@EnableAutoConfiguration:启用自动配置@ComponentScan:组件扫描
3.4 创建第一个Controller
package com.example.myapp.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}注解说明:
@RestController:组合了@Controller和@ResponseBody,返回JSON数据@GetMapping:处理GET请求,等同于@RequestMapping(method = RequestMethod.GET)
3.5 运行应用
方式1:使用IDE运行
- 右键主启动类
- 选择"Run 'MyappApplication'"
- 或点击运行按钮
方式2:使用Maven命令
mvn spring-boot:run方式3:打包后运行
mvn clean package
java -jar target/myapp-0.0.1-SNAPSHOT.jar3.6 测试应用
启动成功后,访问:
http://localhost:8080/hello应该看到输出:Hello, Spring Boot!
3.7 修改默认端口
在application.properties中添加:
server.port=8081或在application.yml中:
server:
port: 80814. Spring Boot核心概念
4.1 自动配置(Auto Configuration)
Spring Boot的自动配置基于条件注解,根据类路径中的jar包自动配置Bean。
自动配置示例
@Configuration
@ConditionalOnClass({DataSource.class, EmbeddedDatabaseType.class})
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {
// 自动配置数据源
}查看自动配置报告
在application.properties中添加:
debug=true启动时会输出自动配置报告。
4.2 起步依赖(Starter Dependencies)
常用Starter
| Starter | 功能 |
|---|---|
| spring-boot-starter-web | Web开发 |
| spring-boot-starter-data-jpa | JPA数据访问 |
| spring-boot-starter-data-redis | Redis |
| spring-boot-starter-security | 安全框架 |
| spring-boot-starter-test | 测试 |
| spring-boot-starter-thymeleaf | Thymeleaf模板 |
自定义Starter
创建自定义starter需要:
- 创建自动配置类
- 创建
spring.factories文件 - 打包发布
4.3 外部化配置
配置文件优先级
- 命令行参数
- 系统属性
- OS环境变量
application-{profile}.propertiesapplication.properties
使用@Value注入配置
@Component
public class MyComponent {
@Value("${app.name}")
private String appName;
@Value("${app.version:1.0.0}") // 默认值
private String appVersion;
}使用@ConfigurationProperties
@ConfigurationProperties(prefix = "app")
@Component
public class AppProperties {
private String name;
private String version;
private List<String> features;
// getter和setter方法
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// ... 其他getter/setter
}配置文件:
app.name=My Application
app.version=1.0.0
app.features=feature1,feature2,feature34.4 Profile配置
创建不同环境的配置
application-dev.properties(开发环境):
server.port=8080
spring.datasource.url=jdbc:h2:mem:testdb
logging.level.root=DEBUGapplication-prod.properties(生产环境):
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
logging.level.root=INFO激活Profile
# 方式1:配置文件
spring.profiles.active=dev
# 方式2:命令行
java -jar app.jar --spring.profiles.active=prod
# 方式3:环境变量
export SPRING_PROFILES_ACTIVE=prod4.5 条件注解
Spring Boot提供了丰富的条件注解:
@ConditionalOnClass(DataSource.class) // 类路径存在时生效
@ConditionalOnMissingBean(DataSource.class) // Bean不存在时生效
@ConditionalOnProperty(name = "app.feature.enabled", havingValue = "true") // 属性为true时生效
@ConditionalOnWebApplication // Web应用时生效
@ConditionalOnExpression("${app.enable:false}") // 表达式为true时生效5. 配置文件管理
5.1 Properties格式
application.properties:
# 服务器配置
server.port=8080
server.servlet.context-path=/api
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# JPA配置
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
# 日志配置
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=app.log5.2 YAML格式
application.yml:
server:
port: 8080
servlet:
context-path: /api
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb
username: root
password: password
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update
show-sql: true
properties:
hibernate:
format_sql: true
logging:
level:
root: INFO
com.example: DEBUG
file:
name: app.log5.3 多环境配置
使用Profile
application.yml:
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
server:
port: 8080
logging:
level:
root: DEBUG
---
spring:
config:
activate:
on-profile: prod
server:
port: 8080
logging:
level:
root: INFO5.4 配置加密
使用Jasypt加密敏感配置:
- 添加依赖:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>- 加密配置:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("mySecretKey");
String encrypted = encryptor.encrypt("myPassword");
System.out.println("ENC(" + encrypted + ")");
}
}- 使用加密值:
spring.datasource.password=ENC(加密后的值)
jasypt.encryptor.password=mySecretKey6. Web开发
6.1 RESTful API开发
创建REST Controller
package com.example.myapp.controller;
import com.example.myapp.model.User;
import com.example.myapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
List<User> users = userService.getAllUsers();
return ResponseEntity.ok(users);
}
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
if (user != null) {
return ResponseEntity.ok(user);
}
return ResponseEntity.notFound().build();
}
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User createdUser = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);
}
@PutMapping("/{id}")
public ResponseEntity<User> updateUser(@PathVariable Long id, @RequestBody User user) {
User updatedUser = userService.updateUser(id, user);
if (updatedUser != null) {
return ResponseEntity.ok(updatedUser);
}
return ResponseEntity.notFound().build();
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
if (userService.deleteUser(id)) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.notFound().build();
}
}常用注解
@RestController:REST控制器@RequestMapping:请求映射@GetMapping:GET请求@PostMapping:POST请求@PutMapping:PUT请求@DeleteMapping:DELETE请求@PathVariable:路径变量@RequestParam:请求参数@RequestBody:请求体@ResponseBody:响应体
6.2 参数绑定
路径变量
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.getUserById(id);
}
@GetMapping("/users/{userId}/posts/{postId}")
public Post getPost(@PathVariable Long userId, @PathVariable Long postId) {
return postService.getPost(userId, postId);
}请求参数
@GetMapping("/users")
public List<User> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "10") int size,
@RequestParam(required = false) String name
) {
return userService.getUsers(page, size, name);
}请求体
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}6.3 异常处理
全局异常处理
package com.example.myapp.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
ErrorResponse error = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
ex.getMessage(),
System.currentTimeMillis()
);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGenericException(Exception ex) {
ErrorResponse error = new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR.value(),
"服务器内部错误",
System.currentTimeMillis()
);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
}
}自定义异常
public class ResourceNotFoundException extends RuntimeException {
public ResourceNotFoundException(String message) {
super(message);
}
}6.4 数据验证
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>使用验证注解
public class User {
@NotNull
@NotBlank
private String name;
@Email
private String email;
@Min(18)
@Max(100)
private Integer age;
@Pattern(regexp = "^1[3-9]\\d{9}$")
private String phone;
// getter和setter
}在Controller中验证
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
return ResponseEntity.ok(userService.createUser(user));
}6.5 跨域配置
方式1:使用@CrossOrigin
@CrossOrigin(origins = "http://localhost:3000")
@RestController
public class UserController {
// ...
}方式2:全局配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("http://localhost:3000")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
}6.6 静态资源
静态资源默认位置:
/static/public/resources/META-INF/resources
访问:http://localhost:8080/static/css/style.css
自定义静态资源路径
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("file:/path/to/files/");
}
}7. 数据访问
7.1 Spring Data JPA
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>配置数据源
application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true创建实体类
package com.example.myapp.model;
import jakarta.persistence.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String email;
private String password;
@Column(name = "created_at")
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
// getter和setter方法
}创建Repository
package com.example.myapp.repository;
import com.example.myapp.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Optional<User> findByEmail(String email);
boolean existsByUsername(String username);
boolean existsByEmail(String email);
}创建Service
package com.example.myapp.service;
import com.example.myapp.model.User;
import com.example.myapp.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
public Optional<User> getUserById(Long id) {
return userRepository.findById(id);
}
public User createUser(User user) {
return userRepository.save(user);
}
public User updateUser(Long id, User userDetails) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("User not found"));
user.setUsername(userDetails.getUsername());
user.setEmail(userDetails.getEmail());
return userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}7.2 MyBatis集成
添加依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>配置MyBatis
application.properties:
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.myapp.model创建Mapper接口
@Mapper
public interface UserMapper {
List<User> findAll();
User findById(Long id);
void insert(User user);
void update(User user);
void delete(Long id);
}创建Mapper XML
src/main/resources/mapper/UserMapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.myapp.mapper.UserMapper">
<select id="findAll" resultType="User">
SELECT * FROM users
</select>
<select id="findById" parameterType="Long" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
<insert id="insert" parameterType="User">
INSERT INTO users (username, email, password)
VALUES (#{username}, #{email}, #{password})
</insert>
</mapper>7.3 Redis集成
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>配置Redis
application.properties:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=
spring.redis.database=0使用RedisTemplate
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public void set(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
}
public Object get(String key) {
return redisTemplate.opsForValue().get(key);
}
public void delete(String key) {
redisTemplate.delete(key);
}
}8. Spring Boot Starter
8.1 常用Starter
Web开发
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>数据访问
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>安全
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>测试
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>8.2 第三方Starter
MyBatis
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>3.0.1</version>
</dependency>Druid连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.18</version>
</dependency>9. 自动配置原理
9.1 @SpringBootApplication注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)
})
public @interface SpringBootApplication {
// ...
}9.2 自动配置流程
- 启动类扫描:扫描
@ComponentScan指定的包 - 加载自动配置:通过
spring.factories加载自动配置类 - 条件判断:根据条件注解决定是否生效
- 创建Bean:创建符合条件的Bean
9.3 查看自动配置
启用调试模式
application.properties:
debug=true启动时会输出自动配置报告。
排除自动配置
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Application {
// ...
}10. 测试
10.1 单元测试
package com.example.myapp.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest
class UserServiceTest {
@Autowired
private UserService userService;
@Test
void testCreateUser() {
User user = new User();
user.setUsername("testuser");
user.setEmail("test@example.com");
User created = userService.createUser(user);
assertNotNull(created.getId());
assertEquals("testuser", created.getUsername());
}
}10.2 集成测试
package com.example.myapp.controller;
import com.example.myapp.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@SpringBootTest
@AutoConfigureMockMvc
class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Test
void testCreateUser() throws Exception {
User user = new User();
user.setUsername("testuser");
user.setEmail("test@example.com");
mockMvc.perform(post("/api/users")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(user)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.username").value("testuser"));
}
}10.3 测试配置
src/test/resources/application-test.properties:
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.hibernate.ddl-auto=create-drop11. 部署与运维
11.1 打包应用
Maven打包
mvn clean package生成jar文件:target/myapp-0.0.1-SNAPSHOT.jar
运行jar包
java -jar target/myapp-0.0.1-SNAPSHOT.jar11.2 生产环境配置
使用外部配置文件
java -jar app.jar --spring.config.location=classpath:/application.properties,file:/path/to/config/application.properties使用环境变量
export SPRING_DATASOURCE_URL=jdbc:mysql://localhost:3306/mydb
java -jar app.jar11.3 Spring Boot Actuator
添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>配置端点
management.endpoints.web.exposure.include=health,info,metrics
management.endpoint.health.show-details=always访问端点
- 健康检查:
http://localhost:8080/actuator/health - 应用信息:
http://localhost:8080/actuator/info - 指标:
http://localhost:8080/actuator/metrics
11.4 Docker部署
创建Dockerfile
FROM openjdk:17-jdk-slim
VOLUME /tmp
COPY target/myapp-0.0.1-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","/app.jar"]构建镜像
docker build -t myapp:1.0.0 .运行容器
docker run -d -p 8080:8080 myapp:1.0.012. 实战项目
12.1 项目需求
创建一个简单的用户管理系统,包含:
- 用户注册
- 用户登录
- 用户信息查询
- 用户信息更新
- 用户删除
12.2 项目结构
user-management/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── usermgmt/
│ │ │ ├── UserManagementApplication.java
│ │ │ ├── controller/
│ │ │ │ └── UserController.java
│ │ │ ├── service/
│ │ │ │ └── UserService.java
│ │ │ ├── repository/
│ │ │ │ └── UserRepository.java
│ │ │ ├── model/
│ │ │ │ └── User.java
│ │ │ └── dto/
│ │ │ └── UserDTO.java
│ │ └── resources/
│ │ └── application.properties
│ └── test/
└── pom.xml12.3 核心代码
实体类
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, unique = true)
private String username;
@Column(nullable = false)
private String email;
private String password;
private LocalDateTime createdAt;
// getter和setter
}Repository
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Optional<User> findByEmail(String email);
}Service
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(User user) {
if (userRepository.existsByUsername(user.getUsername())) {
throw new RuntimeException("用户名已存在");
}
return userRepository.save(user);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
// 其他方法...
}Controller
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@PostMapping
public ResponseEntity<User> createUser(@RequestBody User user) {
User created = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
@GetMapping
public ResponseEntity<List<User>> getAllUsers() {
return ResponseEntity.ok(userService.getAllUsers());
}
// 其他方法...
}13. 常见问题解答
Q: Spring Boot和Spring Framework有什么区别?
A: Spring Boot是Spring Framework的扩展,通过自动配置和起步依赖简化开发,减少配置工作。
Q: 如何自定义自动配置?
A: 创建配置类,使用@ConditionalOn*注解,在META-INF/spring.factories中注册。
Q: 如何排除自动配置?
A: 使用@SpringBootApplication(exclude = {AutoConfiguration.class})或在配置文件中设置。
Q: Spring Boot支持哪些服务器?
A: 支持Tomcat(默认)、Jetty、Undertow。
Q: 如何切换内嵌服务器?
A: 排除Tomcat依赖,添加Jetty或Undertow依赖。
Q: 配置文件优先级是什么?
A: 命令行参数 > 系统属性 > 环境变量 > application-{profile}.properties > application.properties。
Q: 如何实现热部署?
A: 添加spring-boot-devtools依赖,IDE中启用自动构建。
Q: 如何自定义Banner?
A: 在src/main/resources下创建banner.txt文件。
14. 学习资源推荐
官方资源
- Spring Boot官方文档:https://spring.io/projects/spring-boot
- Spring Guides:https://spring.io/guides
- Spring Boot Reference Documentation:https://docs.spring.io/spring-boot/docs/current/reference/html/
推荐书籍
- 《Spring Boot实战》
- 《Spring Boot 2精髓》
- 《深入实践Spring Boot》
在线课程
- Spring官方教程
- 慕课网Spring Boot课程
- B站Spring Boot教程
实践建议
- 多写代码:理论结合实践,多动手编程
- 阅读源码:深入理解Spring Boot原理
- 做项目:通过实际项目巩固知识
- 参与开源:贡献Spring Boot相关项目
- 关注更新:了解Spring Boot新特性
总结
通过本教程,你已经学习了:
✅ Spring Boot的核心概念和特性
✅ 环境搭建和第一个应用
✅ 自动配置和起步依赖
✅ Web开发和RESTful API
✅ 数据访问(JPA、MyBatis、Redis)
✅ 配置文件管理
✅ 测试和部署
✅ 实战项目开发
下一步学习方向:
- 深入学习Spring Boot高级特性
- 学习Spring Cloud微服务
- 学习Spring Security安全框架
- 学习Spring Boot性能优化
- 阅读Spring Boot源码,深入理解原理
记住:Spring Boot是一个强大的框架,需要持续学习和实践。多写代码,多做项目,才能真正掌握Spring Boot开发技能。
本教程持续更新中,如有问题欢迎反馈。祝你学习愉快! 🚀
相关关键词: SpringBoot入门, Spring Boot教程, Spring Boot框架, Spring Boot学习, Spring Boot实战, Spring Boot从零开始, Java Spring Boot, Spring Boot开发, Spring Boot项目, Spring Boot最佳实践