首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 框架架構全解析:核心模塊、設計模式與演進歷程

     編輯:Java 相關知識

前言

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-coreorg.springframework:spring-core基礎工具、資源訪問、類型轉換、異常體系Resource, ResourceLoader, ConversionService, PropertyEditor
spring-beansorg.springframework:spring-beansBeanFactory、BeanDefinition、屬性編輯、工廠模式BeanFactory, BeanDefinition, BeanWrapper, PropertyValues
spring-contextorg.springframework:spring-contextApplicationContext、事件、國際化、驗證、調度、緩存ApplicationContext, MessageSource, ApplicationEventPublisher, TaskScheduler
spring-expressionorg.springframework:spring-expressionSpEL 表達式語言 (EL 3.0 兼容)ExpressionParser, StandardEvaluationContext, SpelExpression

3. 數據訪問/整合模塊

模塊核心功能整合技術
spring-jdbcJDBC 模板、數據源、異常轉換、嵌入式數據庫HikariCP, DBCP2, Tomcat JDBC, H2, HSQLDB
spring-tx事務抽象、PlatformTransactionManager、聲明式/編程式JTA (Atomikos/Bitronix), JDBC, JPA, Hibernate
spring-ormObject/Relational Mapping 整合Hibernate, JPA (Hibernate/EclipseLink), MyBatis, iBATIS
spring-oxmObject/XML MappingJAXB, Jackson XML, XStream, JiBX, Castor
spring-jmsJava Message Service 整合ActiveMQ, RabbitMQ, Artemis, IBM MQ, JMS 2.0

4. Web 模塊演進

模塊定位核心特性適用場景
spring-webWeb 基礎設施Multipart、Servlet API 整合、WebUtilities、Client HttpRequest所有 Web 應用基礎
spring-webmvc傳統 Servlet MVCDispatcherServlet、HandlerMapping、ViewResolver、REST、Interceptor、Matrix Variables同步阻塞 Web 應用 (Spring MVC)
spring-webflux響應式 WebRouterFunction、HandlerFunction、WebClient、Reactor Netty、Server-Sent Events、WebSocket高並發、非阻塞、Reactive Streams
spring-websocketWebSocket 支援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 chain = advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
        // 2. 構建 ReflectiveMethodInvocation
        MethodInvocation invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
        // 3. 執行攔截器鏈
        return invocation.proceed();
    }
}

// CGLIB 代理 (基於繼承)
public class CglibAopProxy implements AopProxy {
    public Object getProxy() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(targetClass);
        enhancer.setCallback(new DynamicAdvisedInterceptor(this));
        return enhancer.create();
    }
}

// 選擇策略:
// - 目標實現接口 → JDK Proxy (默認)
// - proxyTargetClass=true → 強制 CGLIB
// - 無接口 → CGLIB

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.02004-03首個正式版,IoC 容器、AOP、JDBC 模板1.4+
2.02006-10XML 命名空間、AOP Schema、JMS、動態語言支援1.4+
2.52007-11@Component/@Autowired 注解、OSGi、JPA 整合1.5+
3.02009-12Spring EL (SpEL)、Java Config (@Configuration/@Bean)、REST 支援、Portlet5+
3.12011-12Profile、Environment、Cache 抽象、@Enable* 註解5+
4.02013-12Java 8 支援 (Lambda/Stream)、WebSocket、Groovy DSL、泛型類型解析6+
4.32016-06構造器注入自動識別、@AliasFor、Java 9 模塊化準備6+
5.02017-09Spring WebFlux (Reactive)、JDK 9+ 模塊化、Kotlin DSL、HTTP/2、Functional Bean Registration8+
5.22019-09@Configuration(proxyBeanMethods=false)、RSocket、更好的 GraalVM 支援8+
5.32020-10最後一個 Java 8 版本、長期支援至 20248+
6.02022-11Jakarta EE 9+ (javax → jakarta)、Java 17 基線、Observability (Micrometer)、AOT 編譯、GraalVM Native 完整支援17+
6.12023-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
移除已棄用 APIWebMvcConfigurerAdapter 等適配器類移除直接實現接口、使用默認方法
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 的代理攔截鏈,再到事務的模板方法抽象,每個模塊都展示了經典設計模式的工程化落地。

理解模塊架構有助於精準引入依賴、排查類衝突、規劃技術棧升級。掌握設計模式應用能深度理解框架原理、擴展框架功能、設計高質量業務架構。緊跟版本演進則是享受性能提升、安全修復、新特性紅利的前提。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved