src/main/java
└── com.nucsoft.spring.helloworld
├── HelloWorld.java # Bean 類
└── Main.java # 測試類
src/main/resources
└── spring
└── ApplicationContext.xml # Spring 配置文件
Maven pom.xml 核心依賴:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
<!-- 會傳遞引入 spring-beans, spring-core, spring-expression, commons-logging -->
</dependencies>
src/main/resources/spring/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"
xsi:schemaLocation="https://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Bean 定義將在這裡配置 -->
</beans>
package com.nucsoft.spring.helloworld;
/**
* 純 POJO,無任何 Spring 依賴
*/
public class HelloWorld {
private String userName;
// 必須提供 setter,供 IOC 容器注入
public void setUserName(String userName) {
this.userName = userName;
}
public void hello() {
System.out.println("hello: " + userName);
}
}
<?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">
<bean id="helloWorld" class="com.nucsoft.spring.helloworld.HelloWorld">
<!-- setter 注入:property name 對應屬性名,value 對應注入值 -->
<property name="userName" value="spring"/>
</bean>
</beans>
package com.nucsoft.spring.helloworld;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args) {
// 1. 創建 IOC 容器,加載配置文件
ApplicationContext ctx = new ClassPathXmlApplicationContext("spring/ApplicationContext.xml");
// 2. 從容器獲取 Bean(按 id 查找,需強制轉型)
HelloWorld helloWorld = (HelloWorld) ctx.getBean("helloWorld");
// 3. 調用業務方法
helloWorld.hello(); // 輸出: hello:spring
}
}
<bean>,指定類全限定名、id、屬性注入ApplicationContext(IOC 容器)獲取配置好的 Bean 實例| 術語 | 說明 |
|---|---|
| IOC (Inversion of Control) | 控制反轉:對象創建權從應用代碼轉移到容器 |
| DI (Dependency Injection) | 依賴注入:容器自動將依賴注入到對象中(如 setter 注入) |
| Bean | 被 Spring 容器管理的對象 |
| ApplicationContext | Spring 高級容器接口,提供國際化、事件發布、資源加載等 |
| ClassPathXmlApplicationContext | 從類路徑加載 XML 配置的容器實現 |
XML 解析 → 實例化 (無參構造) → 屬性注入 (setter) → 初始化回調 (init-method/InitializingBean) → 就緒使用 → 容器關閉時銷毀 (destroy-method/DisposableBean)
<constructor-arg> 替代 <property>factory-method 屬性指定靜態工廠方法scope="singleton|prototype|request|session"@Component + @Autowired + Java Config,減少 XMLclasspath: 前綴)commons-logging