Spring 框架模組化架構
Spring 採用模組化設計,約 20 個模組可按需引入,核心容器是基礎,其他模組圍繞其構建。
核心容器
| 模組 | 功能 |
| Core | IoC 與依賴注入核心實現 |
| Beans | BeanFactory,工廠模式經典實現 |
| Context | ApplicationContext,提供框架式對象訪問,支援國際化、事件傳播、資源載入 |
| Expression Language (SpEL) | 運行時查詢操作對象圖的強大表達式語言 |
資料存取/整合
| 模組 | 功能 |
| JDBC | JDBC 模板化,消除樣板代碼 |
| ORM | 整合 JPA、Hibernate、MyBatis、JDO |
| OXM | Object/XML 映射:JAXB、Castor、XMLBeans、JiBX、XStream |
| JMS | 訊息生產/消費 |
| Transaction | 程式化/聲明式事務管理 |
Web 層
| 模組 | 功能 |
| Web | 基礎 Web 整合:multipart、Servlet Listener、WebApplicationContext |
| Web-Servlet | Spring MVC 實現 |
| Web-Struts | Struts 1.x 整合 (已過時) |
| Web-Portlet | Portlet 環境下的 MVC |
其他重要模組
- AOP:面向切面程式設計,方法攔截、切點定義
- Aspects:AspectJ 整合
- Instrumentation:類載入器實現、應用伺服器支援
- Test:JUnit/TestNG 整合,Spring TestContext Framework
開發環境搭建步驟
步驟 1:安裝 JDK
步驟 2:安裝 Apache Commons Logging
- 下載:官網
- 解壓並將 JAR 加入 Classpath (Maven/Gradle 專案可忽略,自動解析依賴)
步驟 3:安裝 Eclipse IDE
步驟 4:取得 Spring 框架庫
現代做法:使用建構工具 (強烈推薦)
<!-- Maven pom.xml -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.1.0</version>
</dependency>
</dependencies>
// Gradle build.gradle
dependencies {
implementation 'org.springframework:spring-context:6.1.0'
implementation 'org.springframework:spring-webmvc:6.1.0'
}
傳統做法 (手動下載):
- 下載:Spring 官網
- 解壓,JAR 檔位於
dist/ 目錄
- 加入專案 Build Path 或 Classpath
模組選擇建議
| 專案類型 | 建議模組 |
| 基礎 IoC/DI | spring-context |
| Web MVC | spring-webmvc |
| 資料存取 (JDBC/JPA) | spring-jdbc、spring-orm、spring-tx |
| AOP | spring-aop、aspectjweaver |
| 測試 | spring-test |
| 完整企業應用 | spring-boot-starter-* (推薦 Spring Boot) |
遷移提示:Spring 6 / Spring Boot 3
- 基線:JDK 17+、Servlet 6.0 (Tomcat 10.1+、Jetty 11+)
- 套件命名空間:
javax.* → jakarta.*
- 移除舊模組:
spring-web-struts、spring-jms 部分功能
- 建議直接使用 Spring Boot 3.x 簡化配置