Spring Boot 3X 框架核心組件的使用詳解
Spring Boot 框架核心組件的完整使用詳解,我會聚焦 Spring Boot 最常用、企業(yè)開發(fā)必備的核心組件,從組件核心作用、配置方式、實戰(zhàn)代碼、使用場景四個維度講解,基于Spring Boot 3.2.x(最新穩(wěn)定版,適配 Java 17+、Spring 6),所有代碼都是可直接復(fù)制的開箱即用版本,同時兼顧注解式配置(主流)和核心原理極簡解讀,讓你既能快速上手使用,也能理解組件間的配合邏輯。
前置基礎(chǔ)
Spring Boot 的核心是約定大于配置,通過自動配置(AutoConfiguration) 消除 Spring 原生的繁瑣 XML 配置,所有組件都基于Starter 起步依賴引入,只需少量配置(甚至零配置)即可使用。
- 核心依賴:
spring-boot-starter(基礎(chǔ)核心),所有組件都基于此擴(kuò)展; - 開發(fā)工具:
spring-boot-starter-devtools(熱部署)、spring-boot-configuration-processor(配置提示); - 構(gòu)建方式:Maven/Gradle(本文以 Maven 為例,適配 IDEA 默認(rèn)工程)。
一、核心基礎(chǔ)組件(所有項目必用)
1. Starter 起步依賴(組件入口)
核心作用
Starter 是 Spring Boot 的組件依賴封裝,將某個功能的所有相關(guān)依賴(如核心包、依賴包、配置包)整合為一個 Maven/Gradle 依賴,只需引入 1 個 Starter,即可自動引入該功能的所有必要依賴,避免手動管理依賴版本、解決依賴沖突。
核心設(shè)計
- 命名規(guī)范:官方 Starter 為
spring-boot-starter-*(如spring-boot-starter-web),第三方 Starter 為*spring-boot-starter(如mybatis-spring-boot-starter); - 自動配置:Starter 內(nèi)置
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件,指定該組件的自動配置類,Spring Boot 啟動時會自動加載。
實戰(zhàn)使用(pom.xml)
<!-- 基礎(chǔ)核心Starter(所有Spring Boot項目必加) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Web開發(fā)Starter(MVC+Tomcat,后端接口必加) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 測試Starter(Junit5+MockMvc,單元測試必加) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>2. 主啟動類(@SpringBootApplication)
核心作用
Spring Boot 項目的入口類,通過注解開啟自動配置、組件掃描、配置屬性綁定三大核心功能,是項目啟動的唯一入口。
核心注解拆解(@SpringBootApplication 是復(fù)合注解)
// 核心復(fù)合注解,等價于以下三個注解的組合 @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan
@SpringBootConfiguration:繼承自@Configuration,標(biāo)記該類為配置類,可在類中用@Bean聲明自定義組件;@EnableAutoConfiguration:開啟自動配置,加載所有 Starter 的自動配置類,實現(xiàn) “零配置” 使用組件;@ComponentScan:開啟組件掃描,自動掃描當(dāng)前包及其子包下的@Controller/@Service/@Repository/@Component注解類,將其注冊為 Spring Bean。
實戰(zhàn)使用(主啟動類代碼)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// 注解加在主類上,掃描包:com.example.demo及其所有子包
@SpringBootApplication
// 可選:指定掃描包(若主類不在項目根包,需手動指定)
// @SpringBootApplication(scanBasePackages = "com.example")
public class SpringBootComponentDemoApplication {
// 項目啟動入口方法,固定寫法
public static void main(String[] args) {
// 啟動Spring Boot應(yīng)用,返回Spring容器(ApplicationContext)
SpringApplication.run(SpringBootComponentDemoApplication.class, args);
}
}關(guān)鍵注意
主啟動類建議放在項目根包(如com.example.demo),否則需用scanBasePackages手動指定掃描包,否則子包的組件無法被 Spring 掃描并注冊。
3. 配置文件(application.yml/properties)
核心作用
Spring Boot 的全局配置文件,用于覆蓋組件的默認(rèn)自動配置(如端口、數(shù)據(jù)庫連接、日志級別),支持yml(推薦,層級清晰) 和properties(鍵值對) 兩種格式,項目啟動時會自動加載src/main/resources/下的該文件。
配置優(yōu)先級
application-dev.yml(開發(fā)環(huán)境) > application-prod.yml(生產(chǎn)環(huán)境) > application.yml(全局默認(rèn)),可通過多環(huán)境配置切換不同環(huán)境的配置。
核心使用
(1)基礎(chǔ)配置(application.yml,修改默認(rèn)端口 / 上下文路徑)
# 服務(wù)器配置(覆蓋spring-boot-starter-web的默認(rèn)配置)
server:
port: 8081 # 項目啟動端口,默認(rèn)8080
servlet:
context-path: /demo # 接口上下文路徑,默認(rèn)/,訪問時需加/demo(如http://localhost:8081/demo/hello)
# Spring核心配置
spring:
application:
name: spring-boot-component-demo # 項目名稱,服務(wù)注冊/日志中會使用(2)多環(huán)境配置(最常用,避免開發(fā) / 生產(chǎn)配置混用)
- 新建多環(huán)境配置文件:
- 開發(fā)環(huán)境:
application-dev.yml(本地開發(fā),端口 8081,日志級別 DEBUG) - 生產(chǎn)環(huán)境:
application-prod.yml(線上部署,端口 80,日志級別 INFO)
- 開發(fā)環(huán)境:
- 在
application.yml中指定激活的環(huán)境:
spring:
profiles:
active: dev # 激活開發(fā)環(huán)境,改為prod即切換到生產(chǎn)環(huán)境(3)自定義配置與屬性綁定(@Value/@ConfigurationProperties)
開發(fā)中常需要自定義配置(如自定義接口前綴、業(yè)務(wù)常量),Spring Boot 提供兩種方式綁定到 Java 類:
方式 1:@Value(簡單配置,單個屬性綁定)適合單個 / 少量自定義屬性,直接在 Bean 中注入:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
// 綁定yml中的自定義配置:app.api-prefix
@Value("${app.api-prefix:/api/v1}") // 冒號后為默認(rèn)值,若配置中無該屬性則使用默認(rèn)值
private String apiPrefix;
@GetMapping("/hello")
public String hello() {
return "Hello Spring Boot! 接口前綴:" + apiPrefix;
}
}對應(yīng)的 yml 配置:
# 自定義配置 app: api-prefix: /api/v2
方式 2:@ConfigurationProperties(復(fù)雜配置,批量綁定)適合多個相關(guān)自定義屬性(如微信配置、OSS 配置),批量綁定到一個配置類,更規(guī)范、支持配置提示:步驟 1:編寫配置類,添加注解:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
// 組件注解:將該類注冊為Spring Bean
@Component
// 配置前綴:綁定yml中的wechat節(jié)點下的所有屬性
@ConfigurationProperties(prefix = "wechat")
public class WechatProperties {
// 與yml中的屬性名一致(駝峰自動匹配橫杠命名:app-id → appId)
private String appId;
private String appSecret;
private String mchId; // 商戶號
// 必須提供getter/setter,否則無法綁定(Lombok的@Data可自動生成)
public String getAppId() { return appId; }
public void setAppId(String appId) { this.appId = appId; }
public String getAppSecret() { return appSecret; }
public void setAppSecret(String appSecret) { this.appSecret = appSecret; }
public String getMchId() { return mchId; }
public void setMchId(String mchId) { this.mchId = mchId; }
}步驟 2:yml 中添加對應(yīng)配置:
# 微信配置 wechat: app-id: wx1234567890abcdef app-secret: 1234567890abcdef1234567890abcdef mch-id: 1234567890
步驟 3:在業(yè)務(wù)類中注入使用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WechatController {
// 注入配置類
@Autowired
private WechatProperties wechatProperties;
@GetMapping("/wechat/info")
public String wechatInfo() {
return "微信AppId:" + wechatProperties.getAppId() + ",商戶號:" + wechatProperties.getMchId();
}
}步驟 4:添加配置提示依賴(可選,IDEA 中顯示配置注解,避免手敲錯誤):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>4. 核心注解(Bean 注冊與依賴注入)
Spring Boot 的所有組件都基于Spring IOC 容器,核心是將對象交給 Spring 管理(Bean 注冊) + 從 Spring 容器中獲取對象(依賴注入),以下是最核心的注解,所有業(yè)務(wù)開發(fā)都離不開:
(1)Bean 注冊注解(將類交給 Spring 管理)
標(biāo)記在類上,Spring 啟動時會自動掃描并創(chuàng)建該類的實例,存入 IOC 容器,全局唯一(默認(rèn)單例)。
| 注解 | 作用 | 適用場景 |
|---|---|---|
@Component | 通用 Bean 注冊注解 | 通用工具類、非業(yè)務(wù)層類 |
@Controller | 繼承自 @Component,標(biāo)記控制層 | 接口請求處理類(接收請求、返回響應(yīng)) |
@Service | 繼承自 @Component,標(biāo)記服務(wù)層 | 業(yè)務(wù)邏輯處理類(核心業(yè)務(wù)、事務(wù)控制) |
@Repository | 繼承自 @Component,標(biāo)記數(shù)據(jù)訪問層 | 數(shù)據(jù)庫操作類(DAO/Mapper,MyBatis 中一般用 @Mapper 替代) |
@Configuration | 標(biāo)記配置類 | 聲明自定義 Bean(如第三方組件配置、攔截器配置) |
(2)依賴注入注解(從 Spring 容器中獲取 Bean)
標(biāo)記在字段 / 構(gòu)造方法 /setter 方法上,Spring 會自動從 IOC 容器中找到對應(yīng)的 Bean,注入到當(dāng)前類中,無需手動new對象,實現(xiàn)解耦。
| 注解 | 作用 | 特點 |
|---|---|---|
@Autowired | 按類型注入 Bean | Spring 核心注解,自動匹配類型,支持required = false(非必須注入) |
@Resource | 按名稱注入 Bean(JDK 原生) | 若有多個同類型 Bean,可通過name指定,如@Resource(name = "userServiceImpl") |
@Qualifier | 配合 @Autowired,按名稱注入 | 解決同類型多個 Bean 的注入問題,如@Autowired + @Qualifier("userServiceImpl") |
(3)自定義 Bean 聲明(@Bean)
標(biāo)記在配置類的方法上,用于將第三方組件 / 無注解的類注冊為 Spring Bean(如 RedisTemplate、RestTemplate),方法返回值即為 Bean 實例,方法名為 Bean 名稱。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
// 配置類
@Configuration
public class WebConfig {
// 聲明RestTemplate為Spring Bean,全局可注入使用
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}使用時直接注入:
@Autowired private RestTemplate restTemplate; // 無需new,直接使用
二、Web 開發(fā)核心組件(后端接口必用)
基于spring-boot-starter-web,實現(xiàn) RESTful 接口開發(fā),包含MVC 核心、請求處理、響應(yīng)處理、攔截器、跨域等,是后端開發(fā)最核心的組件。
1. @RestController & @Controller(請求處理核心)
核心區(qū)別
@RestController=@Controller + @ResponseBody:返回 JSON 數(shù)據(jù)(RESTful 接口首選),所有方法的返回值都會自動序列化為 JSON,無需手動加 @ResponseBody;@Controller:返回視圖(傳統(tǒng) SSM 開發(fā),如 JSP/Thymeleaf),適合前后端不分離項目,若需返回 JSON,需在方法上加@ResponseBody。
實戰(zhàn)使用(RESTful 接口)
import org.springframework.web.bind.annotation.*;
// 標(biāo)記為RestController,所有方法返回JSON
@RestController
// 類級別的請求路徑,所有方法的路徑都基于此(如/hello → /user/hello)
@RequestMapping("/user")
public class UserController {
// GET請求:查詢用戶,路徑/ user /get/{id}(路徑參數(shù))
@GetMapping("/get/{id}")
// @PathVariable:獲取URL路徑中的參數(shù)
public String getUser(@PathVariable Long id) {
return "{\"id\":" + id + ", \"name\":\"張三\", \"age\":25}";
}
// POST請求:新增用戶,接收J(rèn)SON參數(shù)
@PostMapping("/add")
// @RequestBody:將請求體的JSON字符串綁定到User對象(自動反序列化)
public String addUser(@RequestBody User user) {
return "新增用戶成功:" + user.getName();
}
// GET請求:分頁查詢,接收請求參數(shù)(如/page?pageNum=1&pageSize=10)
@GetMapping("/page")
// @RequestParam:獲取請求參數(shù),支持默認(rèn)值
public String pageQuery(@RequestParam Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
return "分頁查詢:第" + pageNum + "頁,每頁" + pageSize + "條";
}
}
// 實體類(配合@RequestBody使用,需提供getter/setter,Lombok@Data可簡化)
class User {
private Long id;
private String name;
private Integer age;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setId(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
}核心請求注解(@GetMapping/@PostMapping 等)
都是@RequestMapping的簡化版,指定請求方式,避免在 @RequestMapping 中手動設(shè)置method = RequestMethod.GET:
@GetMapping:處理 GET 請求(查詢)@PostMapping:處理 POST 請求(新增)@PutMapping:處理 PUT 請求(修改)@DeleteMapping:處理 DELETE 請求(刪除)@PatchMapping:處理 PATCH 請求(局部修改)
2. 全局異常處理(@RestControllerAdvice + @ExceptionHandler)
核心作用
統(tǒng)一處理項目中所有的未捕獲異常,避免接口返回默認(rèn)的 500 錯誤頁面 / 雜亂的異常信息,返回統(tǒng)一的 JSON 格式響應(yīng),提升接口的友好性和可維護(hù)性。
核心注解
@RestControllerAdvice:全局異常處理類注解,繼承自@ControllerAdvice,配合@ExceptionHandler使用,返回 JSON 數(shù)據(jù);@ExceptionHandler:標(biāo)記異常處理方法,指定處理的異常類型(如Exception.class處理所有異常,NullPointerException.class處理空指針異常)。
實戰(zhàn)使用(統(tǒng)一異常返回)
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.HashMap;
import java.util.Map;
// 全局異常處理,作用于所有@RestController
@RestControllerAdvice
public class GlobalExceptionHandler {
// 處理所有未捕獲的異常(兜底)
@ExceptionHandler(Exception.class)
public Map<String, Object> handleAllException(Exception e) {
Map<String, Object> result = new HashMap<>();
result.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value()); // 500
result.put("msg", "服務(wù)器內(nèi)部錯誤:" + e.getMessage()); // 異常信息
result.put("data", null);
return result;
}
// 處理自定義業(yè)務(wù)異常(推薦,項目中自定義異常,精準(zhǔn)處理)
@ExceptionHandler(BusinessException.class)
public Map<String, Object> handleBusinessException(BusinessException e) {
Map<String, Object> result = new HashMap<>();
result.put("code", e.getCode()); // 自定義錯誤碼
result.put("msg", e.getMsg()); // 自定義錯誤信息
result.put("data", null);
return result;
}
// 處理空指針異常(精準(zhǔn)處理特定異常)
@ExceptionHandler(NullPointerException.class)
public Map<String, Object> handleNPE(NullPointerException e) {
Map<String, Object> result = new HashMap<>();
result.put("code", 400);
result.put("msg", "空指針異常:" + e.getMessage());
result.put("data", null);
return result;
}
}
// 自定義業(yè)務(wù)異常(項目中建議創(chuàng)建,用于業(yè)務(wù)邏輯錯誤)
class BusinessException extends RuntimeException {
private Integer code;
private String msg;
public BusinessException(Integer code, String msg) {
super(msg);
this.code = code;
this.msg = msg;
}
public Integer getCode() { return code; }
public String getMsg() { return msg; }
}使用自定義異常(業(yè)務(wù)層中拋出)
@Service
public class UserService {
public void deleteUser(Long id) {
if (id == null || id <= 0) {
// 拋出自定義業(yè)務(wù)異常,由全局異常處理器處理
throw new BusinessException(400, "用戶ID不合法");
}
// 業(yè)務(wù)邏輯:刪除用戶
}
}3. 攔截器(Interceptor)
核心作用
攔截接口請求,在請求處理前、處理后、視圖渲染后(Rest 接口無此步驟) 執(zhí)行自定義邏輯,如登錄驗證、接口限流、日志記錄、參數(shù)校驗等。
實現(xiàn)步驟
- 實現(xiàn)
HandlerInterceptor接口,重寫攔截方法; - 在配置類中實現(xiàn)
WebMvcConfigurer接口,重寫addInterceptors方法,注冊攔截器并指定攔截 / 放行路徑。
實戰(zhàn)使用(登錄驗證攔截器)
// 步驟1:實現(xiàn)HandlerInterceptor,編寫攔截邏輯
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginInterceptor implements HandlerInterceptor {
// 核心方法:請求處理前執(zhí)行(return true:放行,return false:攔截)
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// 邏輯:從請求頭獲取token,驗證是否登錄
String token = request.getHeader("token");
if (token == null || token.isEmpty()) {
// 未登錄,返回401錯誤
response.setStatus(401);
response.getWriter().write("{\"code\":401, \"msg\":\"未登錄,請先登錄\", \"data\":null}");
return false; // 攔截請求
}
// 登錄驗證通過,放行
return true;
}
// 可選:請求處理后執(zhí)行(控制器方法執(zhí)行完,未返回響應(yīng)前)
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
// 可選:視圖渲染后執(zhí)行(Rest接口無需實現(xiàn))
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
// 步驟2:配置類中注冊攔截器
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// 注冊攔截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") // 攔截所有路徑
.excludePathPatterns("/user/login", "/user/register"); // 放行登錄/注冊接口
}
}4. 跨域配置(CORS)
核心作用
解決前后端分離項目中的跨域問題(瀏覽器同源策略限制:協(xié)議、域名、端口任一不同即為跨域,如前端http://localhost:3000訪問后端http://localhost:8081)。
實戰(zhàn)實現(xiàn)(兩種方式,推薦全局配置)
方式 1:全局跨域配置(推薦,作用于所有接口)
在WebMvcConfig中重寫addCorsMappings方法:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// 全局跨域配置
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允許所有路徑跨域
.allowedOriginPatterns("*") // 允許所有域名跨域(Spring Boot 2.4+替代allowedOrigins("*"))
.allowedMethods("GET", "POST", "PUT", "DELETE", "PATCH") // 允許的請求方式
.allowedHeaders("*") // 允許的請求頭
.allowCredentials(true) // 允許攜帶Cookie
.maxAge(3600); // 預(yù)檢請求有效期(秒),避免重復(fù)發(fā)送預(yù)檢請求
}
// 攔截器注冊...
}方式 2:局部跨域配置(作用于單個接口 / 控制器)
用@CrossOrigin注解,標(biāo)記在控制器 / 方法上:
// 控制器級別:該類所有接口允許跨域
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*", maxAge = 3600)
public class UserController {
// 方法級別:僅該接口允許跨域(覆蓋控制器級別配置)
@GetMapping("/get/{id}")
@CrossOrigin(origins = "http://localhost:3000")
public String getUser(@PathVariable Long id) {
return "{\"id\":" + id + ", \"name\":\"張三\"}";
}
}三、數(shù)據(jù)訪問核心組件(操作數(shù)據(jù)庫必用)
Spring Boot 提供了多種數(shù)據(jù)訪問組件,適配不同的數(shù)據(jù)庫操作框架,最常用的是 MyBatis-Plus(簡化 MyBatis) 和Spring Data JPA(ORM 框架),以下講解基于MyBatis-Plus(企業(yè)開發(fā)主流,比原生 MyBatis 少寫 80% 代碼)。
1. 核心依賴(MyBatis-Plus + 數(shù)據(jù)庫驅(qū)動 + 連接池)
<!-- MyBatis-Plus Starter(整合MyBatis+自動配置) -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.5</version> <!-- 最新穩(wěn)定版 -->
</dependency>
<!-- MySQL驅(qū)動(適配MySQL8+,5.x需修改版本為5.1.49) -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 阿里Druid連接池(高性能,推薦,替代默認(rèn)的HikariCP) -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.20</version>
</dependency>2. 數(shù)據(jù)庫配置(application.yml)
配置數(shù)據(jù)庫連接、MyBatis-Plus、連接池參數(shù):
spring:
# 數(shù)據(jù)庫連接配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 指定Druid連接池
driver-class-name: com.mysql.cj.jdbc.Driver # MySQL8+驅(qū)動類
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
username: root # 數(shù)據(jù)庫用戶名
password: 123456 # 數(shù)據(jù)庫密碼
# Druid連接池配置
druid:
initial-size: 5 # 初始連接數(shù)
min-idle: 5 # 最小空閑連接數(shù)
max-active: 20 # 最大活躍連接數(shù)
max-wait: 60000 # 最大等待時間(ms)
# MyBatis-Plus配置
mybatis-plus:
mapper-locations: classpath:mapper/*.xml # Mapper.xml文件路徑(若用注解開發(fā)可省略)
type-aliases-package: com.example.demo.entity # 實體類包名,簡化XML中的類名
configuration:
map-underscore-to-camel-case: true # 開啟下劃線轉(zhuǎn)駝峰(數(shù)據(jù)庫user_name → 實體類userName)
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 開啟SQL日志,方便調(diào)試3. 核心注解與使用(MyBatis-Plus)
(1)實體類注解(@TableName/@TableId/@TableField)
標(biāo)記實體類與數(shù)據(jù)庫表的映射關(guān)系:
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
// 映射數(shù)據(jù)庫表:t_user(若實體類名與表名一致,可省略)
@TableName("t_user")
public class User {
// 主鍵注解,type = IdType.AUTO:自增主鍵
@TableId(type = IdType.AUTO)
private Long id;
// 字段注解,若實體類屬性與表字段名一致,可省略
@TableField("user_name")
private String userName;
private Integer age;
private String email;
// getter/setter...
}(2)Mapper 接口(繼承 BaseMapper,零 SQL 實現(xiàn) CRUD)
MyBatis-Plus 的核心,繼承BaseMapper<T>即可獲得單表 CRUD 所有方法,無需手動編寫 Mapper 接口和 XML:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;
// 標(biāo)記為MyBatis Mapper,Spring Boot自動掃描并注冊
@Mapper
public interface UserMapper extends BaseMapper<User> {
// 無需編寫任何方法,BaseMapper已提供所有單表CRUD
// 若需復(fù)雜查詢,可手動編寫方法+XML/注解
}(3)業(yè)務(wù)層使用(注入 Mapper,直接調(diào)用方法)
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
// 新增用戶
public boolean addUser(User user) {
return userMapper.insert(user) > 0;
}
// 根據(jù)ID查詢用戶
public User getUserById(Long id) {
return userMapper.selectById(id);
}
// 條件查詢:根據(jù)姓名模糊查詢,年齡大于20
public List<User> listUser(String name) {
// LambdaQueryWrapper:條件構(gòu)造器,鏈?zhǔn)骄幊?,避免硬編碼字段名
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.like(User::getUserName, name) // 姓名模糊查詢
.gt(User::getAge, 20); // 年齡大于20
return userMapper.selectList(wrapper);
}
// 修改用戶
public boolean updateUser(User user) {
return userMapper.updateById(user) > 0;
}
// 刪除用戶
public boolean deleteUser(Long id) {
return userMapper.deleteById(id) > 0;
}
}4. 事務(wù)管理(@Transactional)
核心作用
保證多個數(shù)據(jù)庫操作的原子性(要么全部成功,要么全部失?。?,避免出現(xiàn)數(shù)據(jù)不一致(如轉(zhuǎn)賬時扣了 A 的錢,沒加 B 的錢)。
實戰(zhàn)使用
標(biāo)記在服務(wù)層方法上(必須在服務(wù)層,控制器層無效),Spring 會自動為該方法添加事務(wù)支持:
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
// 新增用戶并記錄日志,開啟事務(wù)
// rollbackFor = Exception.class:所有異常都回滾(默認(rèn)僅運行時異?;貪L)
@Transactional(rollbackFor = Exception.class)
public boolean addUserAndLog(User user) {
// 操作1:新增用戶
userMapper.insert(user);
// 模擬異常:若出現(xiàn)異常,事務(wù)回滾,用戶不會被新增
// int i = 1 / 0;
// 操作2:記錄日志(假設(shè)有LogMapper)
// logMapper.insert(new Log("新增用戶:" + user.getUserName()));
return true;
}
}核心屬性
rollbackFor = Exception.class:指定所有異常都回滾(默認(rèn)僅RuntimeException和Error回滾,編譯時異常如IOException不回滾,建議必加);propagation:事務(wù)傳播行為(如REQUIRED:默認(rèn),有事務(wù)則加入,無則新建;SUPPORTS:有事務(wù)則加入,無則無事務(wù));readOnly = true:只讀事務(wù)(僅查詢,提升性能)。
四、常用輔助組件(提升開發(fā)效率)
1. 熱部署(spring-boot-starter-devtools)
核心作用
修改代碼 / 配置后,無需手動重啟項目,自動重啟 Spring Boot 應(yīng)用,提升開發(fā)效率(僅開發(fā)環(huán)境使用,生產(chǎn)環(huán)境禁用)。
依賴與配置
<!-- 熱部署依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>yml 配置(可選,優(yōu)化熱部署):
spring:
devtools:
restart:
enabled: true # 開啟熱部署
additional-paths: src/main/java # 監(jiān)聽的代碼目錄
exclude: static/**,templates/** # 排除的目錄(靜態(tài)資源/視圖,修改后無需重啟)IDEA 配置(必做,否則熱部署不生效):
- 開啟自動編譯:File → Settings → Build, Execution, Deployment → Compiler → 勾選Build project automatically;
- 開啟高級自動編譯:按住
Ctrl+Alt+Shift+/→ 選擇 Registry → 勾選compiler.automake.allow.when.app.running。
2. Lombok(簡化代碼,消除樣板代碼)
核心作用
通過注解替代 Java 中繁瑣的getter/setter/toString/ 構(gòu)造方法,減少代碼量,提升開發(fā)效率(需安裝 IDEA Lombok 插件)。
核心依賴與注解
<!-- Lombok依賴 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>常用注解(標(biāo)記在實體類上):
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.ToString;
@TableName("t_user")
@Data // 自動生成getter/setter/equals/hashCode/toString
@NoArgsConstructor // 自動生成無參構(gòu)造方法
@AllArgsConstructor // 自動生成全參構(gòu)造方法
// @ToString // 單獨生成toString(@Data已包含)
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String userName;
private Integer age;
private String email;
}其他常用注解:
@Slf4j:自動生成日志對象log,替代LoggerFactory.getLogger(類名.class);@Builder:開啟建造者模式,可通過User.builder().id(1L).userName("張三").build()創(chuàng)建對象;@NonNull:標(biāo)記字段為非空,賦值為 null 時拋出空指針異常。
3. 接口文檔(Knife4j,替代 Swagger)
核心作用
自動生成RESTful 接口文檔,支持在線調(diào)試、接口測試、文檔導(dǎo)出,替代傳統(tǒng)的 Word 文檔,實現(xiàn)接口文檔與代碼同步更新(Swagger3 的增強(qiáng)版,更適配 Spring Boot 3+)。
核心依賴與配置
<!-- Knife4j Starter(整合Swagger3,適配Spring Boot 3+) -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>4.4.0</version> <!-- 最新穩(wěn)定版 -->
</dependency>配置類(開啟 Swagger3):
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
@Configuration
@EnableWebMvc
@EnableKnife4j // 開啟Knife4j增強(qiáng)功能
public class Knife4jConfig {
// 配置接口文檔基本信息
@Bean
public OpenAPI openAPI() {
return new OpenAPI()
.info(new Info()
.title("Spring Boot組件演示接口文檔")
.description("Spring Boot核心組件實戰(zhàn)接口")
.version("1.0.0"));
}
}yml 配置(開發(fā)環(huán)境開啟,生產(chǎn)環(huán)境關(guān)閉):
knife4j:
enable: true # 開啟Knife4j
openapi:
title: Spring Boot組件演示接口文檔
description: 核心組件實戰(zhàn)接口
version: 1.0.0
spring:
profiles:
active: dev # 開發(fā)環(huán)境開啟,生產(chǎn)環(huán)境改為prod并設(shè)置knife4j.enable=false接口注解(標(biāo)記接口 / 參數(shù),生成更詳細(xì)的文檔)
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
// 接口描述
@Operation(summary = "根據(jù)ID查詢用戶", description = "傳入用戶ID,返回用戶詳細(xì)信息")
// 參數(shù)描述
@Parameters({@Parameter(name = "id", description = "用戶ID", required = true)})
@GetMapping("/get/{id}")
public User getUser(@PathVariable Long id) {
return new User(id, "張三", 25, "zhangsan@163.com");
}
}訪問文檔
項目啟動后,訪問:http://localhost:8081/doc.html(替換為自己的端口 / 上下文路徑),即可看到接口文檔,支持在線調(diào)試(直接填寫參數(shù),點擊 “發(fā)送” 即可測試接口)。
五、Spring Boot 組件核心配合邏輯(一張圖理解)
plaintext
┌─────────────────────────────────────────────────────────┐
│ 客戶端請求(瀏覽器/前端/Postman) │
└───────────────────────────┬─────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────┐
│ 服務(wù)器(Tomcat,由spring-boot-starter-web自動嵌入) │
└───────────────────────────┬─────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────┐
│ 攔截器(Interceptor):登錄驗證/日志記錄/限流 │
└───────────────────────────┬─────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────┐
│ 控制器(@RestController):接收請求/參數(shù)綁定/返回響應(yīng) │
└───────────────────────────┬─────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────┐
│ 服務(wù)層(@Service):業(yè)務(wù)邏輯處理 + 事務(wù)管理(@Transactional)│
└───────────────────────────┬─────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────┐
│ 數(shù)據(jù)訪問層(@Mapper/MyBatis-Plus):操作數(shù)據(jù)庫 │
└───────────────────────────┬─────────────────────────────┘
│
┌───────────────────────────▼─────────────────────────────┐
│ 數(shù)據(jù)庫(MySQL/Redis) │
└─────────────────────────────────────────────────────────┘全局組件兜底:
- 全局異常處理器(@RestControllerAdvice):捕獲所有環(huán)節(jié)的異常,返回統(tǒng)一 JSON;
- 配置文件(application.yml):覆蓋所有組件的默認(rèn)配置;
- Spring IOC 容器:管理所有 Bean,實現(xiàn)依賴注入和解耦。
六、總結(jié)(核心關(guān)鍵點)
- Spring Boot 核心思想:約定大于配置,通過Starter 起步依賴和自動配置消除繁瑣配置,專注業(yè)務(wù)開發(fā);
- 基礎(chǔ)三件套:主啟動類(@SpringBootApplication)+ 配置文件(application.yml)+ 核心注解(Bean 注冊 / 依賴注入),所有項目必用;
- Web 開發(fā)核心:@RestController 實現(xiàn) RESTful 接口,@RestControllerAdvice 實現(xiàn)全局異常處理,Interceptor 實現(xiàn)請求攔截,CORS 解決跨域;
- 數(shù)據(jù)訪問核心:MyBatis-Plus 簡化數(shù)據(jù)庫操作,@Transactional 保證事務(wù)原子性,Druid 作為高性能連接池;
- 效率提升組件:Lombok 消除樣板代碼,devtools 實現(xiàn)熱部署,Knife4j 自動生成接口文檔,都是企業(yè)開發(fā)必備;
- 核心原則:
- 所有組件通過Starter引入,避免手動管理依賴;
- 所有自定義 Bean 通過 **@Configuration + @Bean** 聲明,或通過 @Component 系列注解注冊;
- 所有依賴通過 **@Autowired/@Resource** 注入,無需手動 new,實現(xiàn)解耦;
- 開發(fā)環(huán)境與生產(chǎn)環(huán)境通過多環(huán)境配置分離,避免配置混用。
以上就是 Spring Boot 最核心、最常用的組件使用詳解,覆蓋了從基礎(chǔ)項目搭建到后端接口開發(fā)、數(shù)據(jù)庫操作、效率提升的全流程,所有代碼都可直接復(fù)制到 Spring Boot 3.2.x 項目中使用,適配企業(yè)開發(fā)的主流場景。
到此這篇關(guān)于Spring Boot 3X 框架核心組件的使用詳解的文章就介紹到這了,更多相關(guān)Spring Boot 3X 框架使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決出現(xiàn) java.lang.ExceptionInInitializerError錯誤問題
這篇文章主要介紹了解決出現(xiàn) java.lang.ExceptionInInitializerError錯誤問題的相關(guān)資料,需要的朋友可以參考下2017-01-01
Jexcel實現(xiàn)按一定規(guī)則分割excel文件的方法
這篇文章主要介紹了Jexcel實現(xiàn)按一定規(guī)則分割excel文件的方法,涉及java操作Excel文件的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
SpringBoot之spring.factories的使用方式
這篇文章主要介紹了SpringBoot之spring.factories的使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01
從Mybatis-Plus開始認(rèn)識SerializedLambda的詳細(xì)過程
這篇文章主要介紹了從Mybatis-Plus開始認(rèn)識SerializedLambda,本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-07-07
java中List去除重復(fù)數(shù)據(jù)的5種方式總結(jié)
這篇文章主要給大家總結(jié)介紹了關(guān)于java中List去除重復(fù)數(shù)據(jù)的5種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01

