Spring 3.2.2 版本所需的核心庫(需配合 commons-logging-1.1.1.jar):
雖然文件名可任意,但建議採用語義化命名,便於模塊劃分與維護:
spring-dao.xml —— 數據訪問層 Bean 定義spring-service.xml —— 業務邏輯層 Bean 定義spring.xml —— 總配置,通過 <import> 聚合子配置標準的 beans 约束头部声明(可從官方文檔複製):
<?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">
</beans>
// 讀取 classpath 下的 spring.xml,支持通配符、數組等多種參數形式
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
// 獲取 Bean:推薦使用泛型簽名,避免強轉
HelloDao dao = context.getBean("helloDaoImpl", HelloDao.class);
HelloService service = context.getBean("helloServiceImpl", HelloService.class);
在主配置文件中引入子配置,實現模塊化管理:
<import resource="spring-dao.xml" />
<import resource="spring-service.xml" />
| 屬性 | 說明 | 常用值 |
|---|---|---|
| id | Bean 唯一標識符 | — |
| class | 全限定類名 | — |
| scope | 作用域 | singleton(默認)、prototype、request、session |
| lazy-init | 是否延遲初始化(僅對 singleton 生效) | true、false(default)、default |
scope="singleton" lazy-init="default/false":容器啟動時立即實例化scope="singleton" lazy-init="true":首次 getBean 時才實例化合理使用延遲加載可優化啟動性能,但需注意循環依賴風險。