Spring 框架以「控制反轉(IoC)」與「面向切面程式設計(AOP)」聞名,是 Java 企業級開發的基石。本系列將帶你從零開始,先不依賴 Maven,手動引入 JAR 包、手寫 XML 配置、啟動容器、獲取 Bean,建立最直觀的 Spring 核心認知。後續文章將引入 Maven 管理依賴、註解配置、AOP、事務等進階主題。
Spring 2.5 版本核心僅需一個 `spring.jar`(包含 `spring-core`、`spring-beans`、`spring-context` 等模組)。將其放入專案 `lib` 目錄並加入 Build Path。

在 `src` 目錄下建立 `applicationContext.xml`:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="
https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans-2.5.xsd
https://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- 定義一個 Bean:id 唯一標識,class 全限定類名 -->
<bean id="helloWorld" class="com.lee.spring001.createobject.HelloWorld"></bean>
</beans>
package com.lee.spring001.createobject;
public class HelloWorld {
public HelloWorld() {
System.out.println("HelloWorld... 建構子被呼叫,Bean 實例化");
}
public void hello() {
System.out.println("Hello world!");
}
}
package com.lee.spring001.createobject;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldTest {
@Test
public void testHelloWorld() {
// 1. 載入配置檔,啟動 Spring 容器(完成所有 Bean 實例化、注入)
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// 2. 從容器獲取 Bean(預設單例模式)
HelloWorld hello = (HelloWorld) context.getBean("helloWorld");
// 3. 呼叫業務方法
hello.hello();
}
}
HelloWorld... 建構子被呼叫,Bean 實例化
Hello world!
容器啟動流程:
| 概念 | 說明 |
|---|---|
| Bean | 被 Spring 容器管理的物件,對應 ` |
| IoC 容器 | 負責建立、管理、銷毀 Bean 的核心組件(`ApplicationContext`)。 |
| 依賴查找 | `context.getBean("id")` 主動從容器獲取依賴。 |
| 依賴注入 (DI) | 容器自動將依賴「推」入 Bean(後續文章詳細講解)。 |
完整專案結構與程式碼託管於 GitHub:
https://github.com/leechenxiang/maven-spring001-helloworld
引入 Maven 管理依賴、簡化專案結構,並介紹「構造器注入」與「Setter 注入」兩種 DI 方式,解鎖真正的控制反轉威力。