前言
Spring 框架經過 20 年演進,從最初的輕量級 IoC 容器發展為涵蓋企業級開發各層面的綜合平台。本文系統梳理 Spring 的模塊架構、核心設計模式應用、版本演進里程碑、以及 Spring Boot/Spring Cloud 生態定位。
一、Spring Framework 核心模塊架構 (6.x 版本)
1. 模塊分層架構圖
┌─────────────────────────────────────────────────────────────┐
│ Spring Framework 6.x │
├─────────────────────────────────────────────────────────────┤
│ ┌──────────────┐ ┌──────────────┐ ┌────────────────────┐ │
│ │ Core Container │ │ AOP & │ │ Data Access │ │
│ │ (核心容器) │ │ Aspects │ │ / Integration │ │
│ ├──────────────┤ ├──────────────┤ ├────────────────────┤ │
│ │ spring-core │ │ spring-aop │ │ spring-jdbc │ │
│ │ spring-beans │ │ spring-aspects│ │ spring-tx │ │
│ │ spring-context│ │ │ │ spring-orm │ │
│ │ spring-expression│ │ │ spring-oxm │ │
│ └──────────────┘ └──────────────┘ │ spring-jms │ │
│ └────────────────────┘ │
│ ┌──────────────┐ ┌──────────────┐ ┌────────────────────┐ │
│ │ Web │ │ Testing │ │ Languages │ │
│ │ (Web層) │ │ (測試) │ │ (語言支援) │ │
│ ├──────────────┤ ├──────────────┤ ├────────────────────┤ │
│ │ spring-web │ │ spring-test │ │ spring-groovy │ │
│ │ spring-webmvc│ │ │ │ spring-kotlin │ │
│ │ spring-webflux│ │ │ │ │
│ │ spring-websocket│ │ │ │ │
│ └──────────────┘ └──────────────┘ └────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
2. 核心容器模塊詳解
| 模塊 | Maven 坐標 | 核心功能 | 關鍵類/接口 |
| spring-core | org.springframework:spring-core | 基礎工具、資源訪問、類型轉換、異常體系 | Resource, ResourceLoader, ConversionService, PropertyEditor |
| spring-beans | org.springframework:spring-beans | BeanFactory、BeanDefinition、屬性編輯、工廠模式 | BeanFactory, BeanDefinition, BeanWrapper, PropertyValues |
| spring-context | org.springframework:spring-context | ApplicationContext、事件、國際化、驗證、調度、緩存 | ApplicationContext, MessageSource, ApplicationEventPublisher, TaskScheduler |
| spring-expression | org.springframework:spring-expression | SpEL 表達式語言 (EL 3.0 兼容) | ExpressionParser, StandardEvaluationContext, SpelExpression |
3. 數據訪問/整合模塊
| 模塊 | 核心功能 | 整合技術 |
| spring-jdbc | JDBC 模板、數據源、異常轉換、嵌入式數據庫 | HikariCP, DBCP2, Tomcat JDBC, H2, HSQLDB |
| spring-tx | 事務抽象、PlatformTransactionManager、聲明式/編程式 | JTA (Atomikos/Bitronix), JDBC, JPA, Hibernate |
| spring-orm | Object/Relational Mapping 整合 | Hibernate, JPA (Hibernate/EclipseLink), MyBatis, iBATIS |
| spring-oxm | Object/XML Mapping | JAXB, Jackson XML, XStream, JiBX, Castor |
| spring-jms | Java Message Service 整合 | ActiveMQ, RabbitMQ, Artemis, IBM MQ, JMS 2.0 |
4. Web 模塊演進
| 模塊 | 定位 | 核心特性 | 適用場景 |
| spring-web | Web 基礎設施 | Multipart、Servlet API 整合、WebUtilities、Client HttpRequest | 所有 Web 應用基礎 |
| spring-webmvc | 傳統 Servlet MVC | DispatcherServlet、HandlerMapping、ViewResolver、REST、Interceptor、Matrix Variables | 同步阻塞 Web 應用 (Spring MVC) |
| spring-webflux | 響應式 Web | RouterFunction、HandlerFunction、WebClient、Reactor Netty、Server-Sent Events、WebSocket | 高並發、非阻塞、Reactive Streams |
| spring-websocket | WebSocket 支援 | STOMP、SockJS 落地、消息代理、@MessageMapping | 實時通訊、推送、協作應用 |
二、核心設計模式在 Spring 中的經典應用
1. 工廠模式:Bean 創建的核心
// BeanFactory - 簡單工廠
public interface BeanFactory {
Object getBean(String name) throws BeansException;
T getBean(String name, Class requiredType) throws BeansException;
}
// FactoryBean - 工廠 Bean (產出對象而非自身)
public interface FactoryBean {
T getObject() throws Exception;
Class> getObjectType();
boolean isSingleton();
}
// 典型應用:
// - SqlSessionFactoryBean → SqlSessionFactory
// - LocalContainerEntityManagerFactoryBean → EntityManagerFactory
// - RedisConnectionFactoryBean → RedisConnectionFactory
2. 單例模式:容器級單例管理
// DefaultListableBeanFactory 管理單例緩存
private final Map singletonObjects = new ConcurrentHashMap<>(256);
private final Map earlySingletonObjects = new ConcurrentHashMap<>(16);
private final Map> singletonFactories = new ConcurrentHashMap<>(16);
// 獲取單例 (雙重檢查鎖 + 緩存)
@Override
public Object getSingleton(String beanName, ObjectFactory> singletonFactory) {
Object singleton = singletonObjects.get(beanName);
if (singleton == null) {
synchronized (this.singletonObjects) {
singleton = singletonObjects.get(beanName);
if (singleton == null) {
singleton = singletonFactory.getObject(); // 創建
addSingleton(beanName, singleton);
}
}
}
return singleton;
}
3. 模板方法模式:消除樣板代碼
// JdbcTemplate - 經典模板方法
public class JdbcTemplate extends JdbcAccessor implements JdbcOperations {
// 模板方法:固定流程 (獲取連接 → 預編譯 → 執行 → 釋放)
public T execute(ConnectionCallback action) throws DataAccessException {
Connection con = DataSourceUtils.getConnection(getDataSource());
try {
return action.doInConnection(con); // 變化點:具體 SQL 操作
} catch (SQLException ex) {
throw getExceptionTranslator().translate("execute", null, ex);
} finally {
DataSourceUtils.releaseConnection(con, getDataSource());
}
}
// 回調接口定義變化點
@FunctionalInterface
public interface ConnectionCallback {
T doInConnection(Connection con) throws SQLException;
}
}
// 事務模板
public class TransactionTemplate {
public T execute(TransactionCallback action) {
TransactionStatus status = txManager.getTransaction(definition);
try {
T result = action.doInTransaction(status); // 業務邏輯
txManager.commit(status);
return result;
} catch (RuntimeException | Error ex) {
txManager.rollback(status);
throw ex;
}
}
}
4. 代理模式:AOP 核心實現
// JDK 動態代理 (基於接口)
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 1. 獲取攔截器鏈
List
5. 觀察者模式:事件驅動架構
// ApplicationEventPublisher - 發布者
public interface ApplicationEventPublisher {
void publishEvent(ApplicationEvent event);
void publishEvent(Object event); // Spring 4.2+ 支援任意對象
}
// ApplicationListener - 觀察者
@FunctionalInterface
public interface ApplicationListener extends EventListener {
void onApplicationEvent(E event);
}
// 異步事件執行
@Configuration
public class EventConfig {
@Bean
public ApplicationEventMulticaster applicationEventMulticaster() {
SimpleApplicationEventMulticaster multicaster = new SimpleApplicationEventMulticaster();
multicaster.setTaskExecutor(taskExecutor()); // 異步線程池
return multicaster;
}
}
// 註解式監聽 (Spring 4.2+)
@Component
public class UserEventListener {
@EventListener
public void handleUserRegistered(UserRegisteredEvent event) {
// 異步發送歡迎郵件
}
@EventListener(condition = "#event.user.vipLevel > 5")
public void handleVipUser(UserRegisteredEvent event) {
// VIP 專屬處理
}
}
6. 策略模式:多實現動態切換
// ResourceLoader 策略
public interface ResourceLoader {
Resource getResource(String location);
}
// 不同策略實現:
// - ClassPathResourceLoader: classpath:
// - FileSystemResourceLoader: file:
// - ServletContextResourceLoader: /webapp/
// - UrlResourceLoader: http:/https:/ftp:
// PlatformTransactionManager 策略
// - DataSourceTransactionManager: 本地 JDBC 事務
// - JpaTransactionManager: JPA 事務
// - JtaTransactionManager: 分布式 JTA 事務
// - ChainedTransactionManager: 多資源鏈式事務
// HttpMessageConverter 策略
// - MappingJackson2HttpMessageConverter: JSON
// - StringHttpMessageConverter: 文本
// - ByteArrayHttpMessageConverter: 二進制
// - FormHttpMessageConverter: 表單
// - XmlAwareFormHttpMessageConverter: XML
7. 適配器模式:統一異構接口
// HandlerAdapter - 適配不同 Controller 類型
public interface HandlerAdapter {
boolean supports(Object handler);
ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;
}
// 實現:
// - RequestMappingHandlerAdapter: @RequestMapping/@Controller (主流)
// - HttpRequestHandlerAdapter: HttpRequestHandler 接口
// - SimpleControllerHandlerAdapter: Controller 接口 (舊版)
// - SimpleServletHandlerAdapter: Servlet 適配
// WebMvcConfigurer 添加自定義適配器
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addHandlerAdapters(List adapters) {
adapters.add(new CustomHandlerAdapter());
}
}
8. 裝飾器模式:功能增強
// HttpServletRequestWrapper / HttpServletResponseWrapper
// 標準 Servlet API 裝飾器
// Spring 擴展:
// - ContentCachingRequestWrapper: 緩存請求體 (多次讀取)
// - ContentCachingResponseWrapper: 緩存響應體
// - MutableHttpServletRequest: 可修改請求屬性
// DataSource 裝飾器
public class LazyConnectionDataSourceProxy extends DelegatingDataSource {
// 延遲獲取真實連接,直到真正調用 Statement
@Override
public Connection getConnection() throws SQLException {
return new LazyConnectionProxy(super.getConnection());
}
}
三、版本演進里程碑
| 版本 | 發布時間 | 里程碑特性 | Java 基線 |
| 1.0 | 2004-03 | 首個正式版,IoC 容器、AOP、JDBC 模板 | 1.4+ |
| 2.0 | 2006-10 | XML 命名空間、AOP Schema、JMS、動態語言支援 | 1.4+ |
| 2.5 | 2007-11 | @Component/@Autowired 注解、OSGi、JPA 整合 | 1.5+ |
| 3.0 | 2009-12 | Spring EL (SpEL)、Java Config (@Configuration/@Bean)、REST 支援、Portlet | 5+ |
| 3.1 | 2011-12 | Profile、Environment、Cache 抽象、@Enable* 註解 | 5+ |
| 4.0 | 2013-12 | Java 8 支援 (Lambda/Stream)、WebSocket、Groovy DSL、泛型類型解析 | 6+ |
| 4.3 | 2016-06 | 構造器注入自動識別、@AliasFor、Java 9 模塊化準備 | 6+ |
| 5.0 | 2017-09 | Spring WebFlux (Reactive)、JDK 9+ 模塊化、Kotlin DSL、HTTP/2、Functional Bean Registration | 8+ |
| 5.2 | 2019-09 | @Configuration(proxyBeanMethods=false)、RSocket、更好的 GraalVM 支援 | 8+ |
| 5.3 | 2020-10 | 最後一個 Java 8 版本、長期支援至 2024 | 8+ |
| 6.0 | 2022-11 | Jakarta EE 9+ (javax → jakarta)、Java 17 基線、Observability (Micrometer)、AOT 編譯、GraalVM Native 完整支援 | 17+ |
| 6.1 | 2023-11 | 虛擬線程支援 (Project Loom)、HTTP 介面客戶端、問題詳情 (RFC 7807)、結構化日誌 | 17+ |
四、Spring Boot / Spring Cloud 生態定位
1. Spring Boot:應用開發加速器
Spring Boot ≠ 新框架,而是 Spring Framework 的「約定優於配置」封裝
核心價值:
1. Starter 依賴聚合:spring-boot-starter-web (web+mvc+json+validation+tomcat)
2. 自動配置:@EnableAutoConfiguration 基於類路徑推斷配置 (100+ 自動配置類)
3. 內嵌容器:jar 包直接運行,java -jar app.jar
4. 生產級特性:Actuator、健康檢查、指標、配置外部化
5. 測試切片:@SpringBootTest、@WebMvcTest、@DataJpaTest、@RestClientTest
版本對應:
Spring Boot 3.x → Spring Framework 6.x → Java 17+ → Jakarta EE 9+
Spring Boot 2.7.x → Spring Framework 5.3.x → Java 8+ → Java EE 8 (最後維護版)
2. Spring Cloud:微服務協調平台
Spring Cloud = Spring Boot 上的微服務治理組件套件
版本命名:2020.0, 2021.0, 2022.0, 2023.0 (年份.次序)
對應 Spring Boot:2023.0 → Boot 3.1.x
核心子項目:
- Spring Cloud Netflix (維護模式) → Eureka, Ribbon, Hystrix, Zuul
- Spring Cloud Commons → 服務發現、負載均衡、熔斷抽象
- Spring Cloud Config / Consul Config / Nacos Config / Apollo → 分布式配置
- Spring Cloud Gateway → 反應式 API 閘道 (替代 Zuul)
- Spring Cloud OpenFeign → 聲明式 HTTP 客戶端
- Spring Cloud CircuitBreaker → Resilience4j/Sentinel 適配
- Spring Cloud Stream → 事件驅動微服務 (Kafka/RabbitMQ/Pulsar)
- Spring Cloud Function → FaaS 函數抽象
- Spring Cloud Kubernetes → K8s 原生整合
- Spring Cloud Security / OAuth2 → 統一認證授權
- Spring Cloud Sleuth / Zipkin / SkyWalking → 分布式追蹤
五、Spring Framework 6.x / Boot 3.x 關鍵變更
| 變更點 | 影響 | 遷移指南 |
| javax.* → jakarta.* | 所有 Java EE API 包名變更 | 批量重命名導入、更新依賴坐標 (javax.servlet → jakarta.servlet) |
| Java 17 基線 | 需 JDK 17+ 運行/編譯 | 升級 JDK、更新 maven-compiler-plugin release=17 |
| 移除已棄用 API | WebMvcConfigurerAdapter 等適配器類移除 | 直接實現接口、使用默認方法 |
| Observability 整合 | Micrometer 內建,Actuator 指標標準化 | 遷移自定義指標到 Micrometer API |
| AOT 編譯支援 | spring-aot-maven-plugin 預處理 | 啟用 native profile、配置 GraalVM |
| 虛擬線程支援 | Spring 6.1+ 支援 Project Loom | 配置 Tomcat/Jetty 使用虛擬線程、@EnableVirtualThreads |
| HTTP 介面客戶端 | @HttpExchange 聲明式客戶端 (替代 Feign 輕量級) | 定義接口 + @GetExchange/@PostExchange |
總結
Spring 框架架構體現了「高內聚、低耦合、可擴展」的軟件工程精髓。從核心容器的 BeanDefinition 元數據模型,到 AOP 的代理攔截鏈,再到事務的模板方法抽象,每個模塊都展示了經典設計模式的工程化落地。
理解模塊架構有助於精準引入依賴、排查類衝突、規劃技術棧升級。掌握設計模式應用能深度理解框架原理、擴展框架功能、設計高質量業務架構。緊跟版本演進則是享受性能提升、安全修復、新特性紅利的前提。