定义与作用
Spring 是一个开源的 Java 框架,用于简化企业级 Java 应用程序的开发。它通过提供全面的基础设施支持,使开发者能够专注于业务逻辑层的开发,而非底层的复杂技术实现。
核心特点
轻量级:Spring 框架本身体积小,启动速度快。
非侵入式:基于 POJO(普通 Java 对象)开发,无需实现特定接口或继承特定类。
模块化架构:由多个核心模块组成,如 Core Container(核心容器)、Data Access/Integration(数据访问/集成)、Web 等,每个模块解决特定问题,使用者可以根据需要选择模块组合。
依赖注入(DI)和控制反转(IoC):作为 Spring 核心概念之一,IoC 容器负责管理依赖关系,将组件的创建和管理从应用程序代码中分离出来。
适用场景
适合各种规模的企业级应用开发,尤其是需要与其他框架和技术集成的复杂项目。
适用于需要高效管理依赖关系、实现松耦合的系统架构的设计。
对于需要快速开发、测试驱动开发和持续集成的项目极为有益。
Spring 生态系统组成
Spring Framework:核心框架,包含 Bean 容器、AOP、IoC、上下文等基础功能。
Spring Boot:简化配置,快速构建独立的、生产级别的 Spring 应用程序,内置了嵌入式的 Servlet 容器,自动化配置。
Spring Data:简化对不同数据存储(如关系型数据库、NoSQL 数据库等)的访问。
Spring Security:提供认证、授权和安全控制功能,保障应用安全性。
Spring Cloud:基于 Spring Boot 的微服务架构解决方案,包含服务注册发现、配置管理、路由管理等功能。
Spring Batch:用于高效处理批量数据处理任务。
确保安装了最新版本的 JDK(官网下载地址链接),并配置系统环境变量 JAVA_HOME
和 PATH
(将 JDK 安装路径添加到 PATH
中)。
IntelliJ IDEA:
推荐版本:Ultimate 或 Community 版。
特点:
强大的代码自动补全和重构功能。
对 Spring 框架有优质的支持,包括项目创建向导、依赖管理、代码模板等。
内置了对 Git、Maven/Gradle 等工具的支持。
安装步骤:
下载安装包并按向导完成安装。
启动后,根据提示更新插件,安装必要的插件如 Lombok 支持、Spring Assistant(辅助开发 Spring 项目的插件)等。
Eclipse:
推荐版本:Eclipse IDE for Enterprise Java Developers。
特点:
轻量化,可自定义界面和插件。
提供了丰富的插件市场,支持 Spring 工具套件(Spring Tools Suite)。
集成了 Mylyn 工具,帮助开发者集中精力在任务相关的代码上。
安装步骤:
安装 Eclipse IDE 基础版本后,通过 Eclipse Marketplace
安装 Spring Tools
和其他相关插件。
Git 安装与配置
下载地址:Git 官网。
安装并配置用户信息:
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
初始化本地仓库:
git init
远程仓库关联与推送:
bash复制
git remote add origin
git push -u origin master
推荐使用 Maven 或 Gradle 管理项目依赖和构建过程。
Maven:
安装步骤:下载 Maven 二进制包,解压后配置环境变量 MAVEN_HOME
,将 %MAVEN_HOME%\bin
添加到 PATH
环境变量中。
配置文件:settings.xml
可配置本地仓库位置、私服等信息,存储在 %USERPROFILE%\.m2\
目录下。
常用命令:
mvn compile # 编译项目
mvn clean # 清理目标目录
mvn package # 打包项目
mvn install # 安装到本地仓库
Gradle:
通过 IDE 自带的插件支持或手动安装,配置环境变量 GRADLE_HOME
。
使用 build.gradle
文件定义项目依赖和任务。
常用命令:
gradle build # 构建项目
gradle clean # 清理构建目录
打开 Spring Initializr 网站:
Project:选择 Maven 或 Gradle(Maven 使用更广泛)。
Language:选择 Java 或 Kotlin,Groovy(推荐使用 Java)。
Spring Boot 版本:选取合适的小版本(如 3.2.0)。
项目信息:
Group:组织标识符,如 com.example
。
Artifact:项目名称,如 spring-boot-demo
。
Name:项目名称(可留空)。
Description:项目描述。
Package Name:主包名。
Packaging:Jar
或 War
(Web 应用程序通常选 Jar
,无须单独部署到服务器)。
Java Version:JDK 版本。
Dependencies:选择项目所需依赖:
Spring Web
:支持基于 Spring MVC 的 Web 开发。
Spring Data JPA
:简化数据访问。
H2 Database
:嵌入式数据库,用于学习和测试。
Lombok
:减少样板代码。
Thymeleaf
:模板引擎。
点击 “Generate” 下载项目压缩包,解压后导入到 IDE 中(IntelliJ IDEA 能自动识别为 Maven 项目)。
src/main/java:
包名对应 Package Name
,如 com.example.springboootdemo
。
主类(Application.java
)通常位于最外层包下,带有 @SpringBootApplication
注解,用于启动项目。
src/main/resources:
application.properties:配置文件,存储项目运行时参数。
static:存放前端静态资源(CSS、JS、图像等)。
templates:存放 Thymeleaf 模板文件。
创建 Controller 在 controller
包下新建类 HelloController
,代码如下:
package com.example.springbootdemo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
启动项目 右键主类 Application.java
,选择 “运行” 或通过命令行运行:
bash复制
mvn spring-boot:run
打开浏览器访问 http://localhost:8080/hello
,应显示 “Hello, World!”。
在模型包下(如 model
包)创建实体类 User
,使用 JPA 注解:
package com.example.springbootdemo.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Column;
@Entity // 表明该类是一个 JPA 实体
public class User {
@Id // 主键
@GeneratedValue(strategy = GenerationType.AUTO) // 自动生成主键
private Long id;
@Column // 对应数据库表里的列
private String name;
@Column
private String email;
// 构造方法、getter、setter
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
// getter 和 setter 方法
}
在 repository
包下创建 UserRepository
接口,继承 JpaRepository
:
package com.example.springbootdemo.repository;
import com.example.springbootdemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository {
// 无需编写实现代码,Spring Data JPA 会自动实现
}
在 service
包下创建 UserService
类,使用 @Service
注解:
package com.example.springbootdemo.service;
import com.example.springbootdemo.model.User;
import com.example.springbootdemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User createUser(User user) {
return userRepository.save(user);
}
public List getAllUsers() {
return userRepository.findAll();
}
public User updateUser(User user) {
return userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
在 HelloController
中注入 UserService
并调用方法:
package com.example.springbootdemo.controller;
import com.example.springbootdemo.model.User;
import com.example.springbootdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class HelloController {
private final UserService userService;
@Autowired
public HelloController(UserService userService) {
this.userService = userService;
}
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
@GetMapping("/users")
public List getAllUsers() {
return userService.getAllUsers();
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.updateUser(user);
}
@DeleteMapping("/users/{id}")
public void deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
}
}
在 application.properties
文件中配置 H2 数据库:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true # 启用 H2 控制台
spring.jpa.hibernate.ddl-auto=update # 自动更新数据库结构
资源命名:使用名词(复数形式),如 /users
,避免使用动词。
HTTP 方法映射:
GET
:获取资源。
POST
:创建资源。
PUT
:更新资源。
DELETE
:删除资源。
状态码:
200 OK
:表示资源已经存在,如获取/更新/删除操作。
201 Created
:创建资源成功。
404 Not Found
:资源未找到。
400 Bad Request
:客户端请求参数错误。
路径变量(Path Variable):
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
请求参数(Request Parameter):
@GetMapping("/users")
public List getUsersByPage(@RequestParam int page, @RequestParam int size) {
return userService.getUsersByPage(page, size);
}
请求体(Request Body):
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.createUser(user);
}
返回 JSON 格式数据:
@RestController
public class HelloController {
@GetMapping("/users")
public List getUsers() {
return userService.getAllUsers();
}
}
返回自定义响应消息:
@PostMapping("/users")
@ResponseBody
public ApiResponse createUser(@RequestBody User user) {
return new ApiResponse(201, "User created successfully", user);
}
编写 JUnit 测试用例,测试 Service 层:
package com.example.springbootdemo.service;
import com.example.springbootdemo.model.User;
import com.example.springbootdemo.repository.UserRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
public class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@BeforeEach
public void setUp() {
MockitoAnnotations.openMocks(this);
}
@Test
public void testGetAllUsers() {
User user1 = new User("Alice", "[email protected]");
User user2 = new User("Bob", "[email protected]");
when(userRepository.findAll()).thenReturn(Arrays.asList(user1, user2));
List users = userService.getAllUsers();
assertEquals(2, users.size());
}
@Test
public void testCreateUser() {
User user = new User("Charlie", "[email protected]");
when(userRepository.save(user)).thenReturn(user);
User savedUser = userService.createUser(user);
assertNotNull(savedUser);
}
}
使用 Spring Boot Test 模块,测试 Controller 层:
package com.example.springbootdemo.controller;
import com.example.springbootdemo.model.User;
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.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetUsers() throws Exception {
mockMvc.perform(get("/users"))
.andExpect(status().isOk())
.andExpect(jsonPath("$").isArray());
}
@Test
public void testCreateUser() throws Exception {
String jsonUser = "{\"name\":\"Tom\",\"email\":\"[email protected]\"}";
mockMvc.perform(post("/users")
.contentType("application/json")
.content(jsonUser))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Tom"));
}
}
设置断点:在 IDE 中,在关键代码行(如方法开头、控制语句)右键设置断点。
逐行调试:按 F7
或 F8
(IntelliJ IDEA),逐行执行代码,观察变量值。
查看执行栈:在调试视图中查看调用栈信息,分析问题根源。
日志输出:合理配置日志级别(ERROR
、WARN
、INFO
、DEBUG
等),通过日志文件排查问题。
通过 @Conditional
注解,根据条件加载配置:
@Configuration
@ConditionalOnProperty(name = "spring.application.profile", havingValue = "dev")
public class DevelopmentConfig {
@Bean
public UserProfile userProfile() {
return new UserProfile("development");
}
}
为不同环境(开发/测试/生产)配置不同的属性,配置文件:
application-dev.properties
:开发环境配置。
application-test.properties
:测试环境配置。
application-prod.properties
:生产环境配置。 在主配置文件中指定激活环境:
spring.profiles.active=dev
集成 Spring Cache 加速应用:
@Cacheable("users")
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
使用 Spring Security 保护应用:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.requestMatchers("/admin/**").hasRole("ADMIN")
.requestMatchers("/user/**").hasRole("USER")
.and()
.formLogin();
return http.build();
}
}
Thymeleaf:在模板中嵌入 Spring 表达式:
Default Name
Vue.js:前端工程化开发,通过 REST API 获取数据,配合 Spring Boot 提供后端服务。
遵循 RESTful 规范,设计资源导向的 URL 结构:
GET /api/books
:获取所有书籍。
POST /api/books
:创建新书籍。
PUT /api/books/{id}
:更新指定书籍。
DELETE /api/books/{id}
:删除指定书籍。
使用 @ControllerAdvice
和 @ExceptionHandler
全局处理异常:
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity
配置日志框架(如 Logback),记录应用运行日志:
logging.level.root=INFO
logging.level.com.example=DEBUG
logging.file.name=application.log
使用 Maven 或 Gradle 将应用打包为 JAR/WAR 文件:
mvn clean package
Tomcat:将 WAR 文件部署到 Tomcat 的 webapps
目录。
Jetty:类似 Tomcat 操作。
Docker:构建 Docker 镜像并部署:
FROM openjdk:17-jdk-slim
COPY target/spring-boot-demo.jar app.jar
ENTRYPOINT ["java", "-jar", "app.jar"]
使用 Spring Boot Actuator 监控应用:
添加依赖 spring-boot-starter-actuator
。
访问监控端点:
curl http://localhost:8080/actuator/health
curl http://localhost:8080/actuator/metrics