Spring 是一個輕量級容器框架,核心職責:管理 Bean 的創建、裝配與生命周期,解決對象間耦合問題。

src/ ├── com.server.User # POJO ├── com.test.Test # 測試類 └── applicationContext.xml # 容器配置文件
package com.server;
public class User {
private String name;
public void getName() { System.out.println("Hello " + name); }
public void setName(String name) { this.name = name; }
}
<?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">
<!-- id: Bean 唯一標識;class: 全限定類名 -->
<bean id="user" class="com.server.User">
<!-- setter 注入:name 屬性對應 setName() -->
<property name="name">
<value>chauncy</value>
</property>
</bean>
</beans>
等價於:User user = new User(); user.setName("chauncy");
package com.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.server.User;
public class Test {
public static void main(String[] args) {
// 載入配置文件,初始化容器
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// 根據 id 獲取 Bean,自動完成實例化與屬性注入
User user = (User) ac.getBean("user");
user.getName(); // 輸出:Hello chauncy
}
}
| 概念 | 說明 |
|---|---|
| IoC (Inversion of Control) | 控制反轉:對象創建權從應用代碼移交給容器 |
| DI (Dependency Injection) | 依賴注入:容器自動將依賴對象注入目標對象(如上例 setter 注入) |
| ApplicationContext | 高級容器接口,提供國際化、事件發布、資源加載等企業級功能 |
| BeanDefinition | Bean 的元數據描述(類名、作用域、構造參數、屬性值等) |
@Component + @Autowired 替代 XML。@Configuration + @Bean 類型安全配置。init-method、destroy-method 或 @PostConstruct/@PreDestroy。