首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring 入門(二):首個案例前的準備工作

     編輯:Java 相關知識

核心 JAR 包依賴

Spring 3.2.2 版本所需的核心庫(需配合 commons-logging-1.1.1.jar):

  • spring-beans-3.2.2.RELEASE.jar
  • spring-context-3.2.2.RELEASE.jar
  • spring-context-support-3.2.2.RELEASE.jar
  • spring-core-3.2.2.RELEASE.jar
  • spring-expression-3.2.2.RELEASE.jar

配置文件命名建議

雖然文件名可任意,但建議採用語義化命名,便於模塊劃分與維護:

  • spring-dao.xml —— 數據訪問層 Bean 定義
  • spring-service.xml —— 業務邏輯層 Bean 定義
  • spring.xml —— 總配置,通過 <import> 聚合子配置

Spring 配置文件的 XML Schema 宣告

標準的 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>

容器實例化與 Bean 獲取

// 讀取 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> 標籤

在主配置文件中引入子配置,實現模塊化管理:

<import resource="spring-dao.xml" />
<import resource="spring-service.xml" />

Bean 核心屬性詳解

屬性說明常用值
idBean 唯一標識符—
class全限定類名—
scope作用域singleton(默認)、prototype、request、session
lazy-init是否延遲初始化(僅對 singleton 生效)true、false(default)、default

scope 與 lazy-init 組合行為

  • scope="singleton" lazy-init="default/false":容器啟動時立即實例化
  • scope="singleton" lazy-init="true":首次 getBean 時才實例化

合理使用延遲加載可優化啟動性能,但需注意循環依賴風險。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved