Spring 核心是控制反轉 (IoC) 容器,負責建立、管理 Bean 生命週期與依賴關係。本文通過最簡單的 HelloWorld 案例,揭示「工廠模式」如何取代傳統 new 方式,降低耦合度。
src/ ├─ com.qinb.service │ └─ HelloWorld.java ├─ beans.xml └─ Test.java

beans.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"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 相當於實例化 HelloWorld 類 -->
<bean id="helloWorld" class="com.qinb.service.HelloWorld" />
</beans>
關鍵點: id 為 Bean 唯一標識,class 指定全限定類名。慣例 id 使用駝峰首字母小寫。
HelloWorldpackage com.qinb.service;
public class HelloWorld {
public void say() {
System.out.println("Hello, Spring IoC!");
}
}

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.qinb.service.HelloWorld;
public class Test {
public static void main(String[] args) {
// 1. 啟動容器,載入配置
ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
// 2. 依 id 獲取 Bean(注意大小寫)
HelloWorld hw = (HelloWorld) ac.getBean("helloWorld");
// 3. 呼叫業務方法
hw.say();
}
}

| 傳統方式 | Spring IoC 方式 |
|---|---|
調用方 new HelloWorld() | 容器負責實例化,調用方僅獲取 |
| 依賴具體實現類 | 依賴抽象/介面,實現類可替換 |
| 物件生命週期自管 | 容器統一管理(單例、原型、初始化/銷毀回調) |
比喻: 傳統方式像「餓了自己做筷子」,Spring 像「筷子備好放抽屜,需要時直接拿」。統一管理、按需獲取,大型專案中極大降低維護成本。
setter 注入、建構子注入、@Autowired 註解注入。InitializingBean、DisposableBean、@PostConstruct/@PreDestroy。@Component、@Configuration、@Bean 取代 XML。掌握 IoC 容器運作機制,是精通 Spring 生態的基石。