Spring Boot从入门到精通:Java程序员必备指南
目录
-
Spring Boot 简介
-
环境准备
-
第一个 Spring Boot 应用
-
核心特性详解
-
Web 开发实战
-
数据访问与持久化
-
测试
-
高级主题
-
部署与监控
-
最佳实践与常见问题
-
总结与学习资源
1. Spring Boot 简介
Spring Boot 是基于 Spring 框架的快速开发脚手架,它遵循“约定优于配置”的原则,帮助开发者避免繁琐的 XML 配置。主要优势包括:
-
起步依赖(Starter):聚合常用依赖,简化 Maven/Gradle 配置。
-
自动配置(Auto-Configuration):根据类路径、Bean 等自动配置 Spring 组件。
-
嵌入式服务器:内置 Tomcat、Jetty 或 Undertow,可直接运行 JAR 包。
-
生产级特性:提供健康检查、指标监控、外部化配置等。
2. 环境准备
-
JDK:8 或 11(Spring Boot 2.x),17(Spring Boot 3.x)
-
构建工具:Maven 3.5+ 或 Gradle 6+
-
IDE:IntelliJ IDEA、Eclipse、VS Code 均可(推荐 IDEA)
-
可选:Postman(测试 API)、Docker(容器化部署)
3. 第一个 Spring Boot 应用
3.1 使用 Spring Initializr 创建项目
访问 start.spring.io,选择:
-
Project:Maven
-
Language:Java
-
Spring Boot:选择稳定版(如 3.2.x)
-
Group:com.example
-
Artifact:demo
-
Dependencies:Spring Web(用于构建 REST API)
点击生成,下载 ZIP 并解压,用 IDE 打开。
3.2 项目结构
demo/
├── src/main/java/com/example/demo/
│ └── DemoApplication.java # 启动类
├── src/main/resources/
│ ├── application.properties # 配置文件
│ └── static/ # 静态资源
│ └── templates/ # 模板文件
└── pom.xml
3.3 编写第一个 REST 接口
在 DemoApplication 同级或子包下创建 HelloController.java:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}
3.4 运行应用
执行 DemoApplication.main(),控制台看到启动日志后,访问 http://localhost:8080/hello,即可看到响应。
4. 核心特性详解
4.1 启动类与 @SpringBootApplication
@SpringBootApplication 是一个组合注解,包含:
-
@Configuration:声明配置类 -
@EnableAutoConfiguration:启用自动配置 -
@ComponentScan:自动扫描当前包及子包中的组件
4.2 起步依赖
在 pom.xml 中引入 spring-boot-starter-* 即可获得一组兼容的依赖。例如:
-
spring-boot-starter-web:包含 Spring MVC、Jackson、Tomcat -
spring-boot-starter-data-jpa:包含 Hibernate、Spring Data JPA、HikariCP
4.3 配置文件
Spring Boot 支持 application.properties 或 application.yml。常用配置:
# 修改端口
server.port=8081
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
也可以使用 YAML 格式(更简洁):
server:
port: 8081
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
4.4 日志
默认使用 Logback,可在配置文件中设置级别:
logging.level.com.example=DEBUG
logging.file.name=app.log
5. Web 开发实战
5.1 创建 RESTful API
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List<User> listUsers() { ... }
@PostMapping
public User createUser(@RequestBody User user) { ... }
@GetMapping("/{id}")
public User getUser(@PathVariable Long id) { ... }
}
5.2 参数校验
使用 Jakarta Bean Validation(Spring Boot 3.x):
public class User {
@NotNull
@Size(min=2, max=20)
private String name;
@Email
private String email;
}
在 Controller 中启用校验:
@PostMapping
public User createUser(@Valid @RequestBody User user) { ... }
5.3 统一异常处理
使用 @ControllerAdvice 处理全局异常:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleValidationExceptions(MethodArgumentNotValidException ex) {
Map<String, String> errors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error ->
errors.put(error.getField(), error.getDefaultMessage()));
return ResponseEntity.badRequest().body(errors);
}
}
5.4 视图渲染(Thymeleaf)
引入 spring-boot-starter-thymeleaf,在 resources/templates 下创建 HTML 文件,即可使用 Thymeleaf 语法。
6. 数据访问与持久化
6.1 使用 Spring Data JPA
引入 spring-boot-starter-data-jpa 和数据库驱动(如 MySQL)。
配置数据源后,创建实体类:
@Entity
public class User {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String name;
// getters/setters
}
创建 Repository 接口:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> findByName(String name);
}
无需实现,Spring Data JPA 会在运行时自动生成实现类。
6.2 事务管理
在 Service 方法上添加 @Transactional:
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional
public void updateUser(...) { ... }
}
6.3 数据库连接池
Spring Boot 默认使用 HikariCP,只需在配置文件中指定连接池参数:
spring.datasource.hikari.maximum-pool-size=10
7. 测试
7.1 单元测试
引入 spring-boot-starter-test,它包含 JUnit、Mockito、AssertJ 等。
测试 Service 层:
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetUser() throws Exception {
mockMvc.perform(get("/api/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"));
}
}
7.2 切片测试
使用 @WebMvcTest 仅测试 Controller 层,使用 @DataJpaTest 仅测试 Repository 层,加快测试速度。
8. 高级主题
8.1 安全性(Spring Security)
引入 spring-boot-starter-security,默认所有端点需要认证。可自定义配置:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.formLogin(Customizer.withDefaults());
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
UserDetails user = User.withUsername("user")
.password("{noop}password") // {noop} 表示明文
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
8.2 缓存
启用缓存:在主类上添加 @EnableCaching。
在方法上使用 @Cacheable:
@Cacheable("users")
public User findById(Long id) { ... }
需要配置缓存实现,如 Ehcache、Redis 等。
8.3 消息队列
以 RabbitMQ 为例:引入 spring-boot-starter-amqp,配置连接信息。
发送消息:
@Autowired
private RabbitTemplate rabbitTemplate;
rabbitTemplate.convertAndSend("exchange", "routingKey", message);
接收消息:
@RabbitListener(queues = "queueName")
public void handleMessage(String message) { ... }
8.4 异步处理
在主类添加 @EnableAsync,在方法上使用 @Async 即可让方法在独立线程中执行。
需要配置线程池:
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
return executor;
}
8.5 Actuator 监控
引入 spring-boot-starter-actuator,即可通过 /actuator 端点获取应用健康、指标、环境等信息。
配置暴露所有端点:
management.endpoints.web.exposure.include=*
9. 部署与监控
9.1 打包为 JAR 运行
使用 Maven 打包:mvn clean package,生成 target/demo-0.0.1-SNAPSHOT.jar。
运行:java -jar demo.jar。
9.2 打包为 WAR 部署
修改打包方式为 war,并继承 SpringBootServletInitializer,然后部署到外部容器。
9.3 容器化
编写 Dockerfile:
FROM openjdk:17-jdk-slim
COPY target/demo.jar app.jar
ENTRYPOINT ["java", "-jar", "/app.jar"]
构建镜像:docker build -t demo .
运行容器:docker run -p 8080:8080 demo
10. 最佳实践与常见问题
-
配置分离:使用
application-{profile}.properties区分环境,通过spring.profiles.active激活。 -
使用 Lombok:简化 POJO 代码(添加
@Data、@Builder等)。 -
分层架构:Controller → Service → Repository,保持职责清晰。
-
避免字段注入:推荐构造器注入,便于测试。
-
数据库版本管理:集成 Flyway 或 Liquibase。
-
常见问题:
-
端口冲突:修改
server.port -
数据库连接失败:检查驱动、URL、认证信息
-
自动配置失效:查看自动配置报告(
--debug启动)
-
11. 总结与学习资源
通过本教程,你已经掌握了 Spring Boot 的核心知识与常用组件。从创建第一个应用,到数据访问、安全、消息、监控,你已经具备了构建企业级应用的基础。
继续深入,可以关注:
-
Spring Guides:一系列实战教程
-
开源项目:阅读优秀项目的源码,如 Spring PetClinic
Spring Boot 的世界广阔而精彩,愿你在实践中不断成长,成为一名真正的 Spring Boot 专家!
希望这份教程能成为你 Spring Boot 学习之路的可靠伙伴。如有任何疑问,欢迎在评论区留言交流。Happy Coding!
更多推荐




所有评论(0)