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

Spring 4.x 開發環境搭建完整指南:從 Jar 引入到 Web.xml 配置

     編輯:Java 綜合教學

前言

本文記錄在 Eclipse 中建立動態 Web 專案並整合 Spring 4.1 的完整步驟,涵蓋 Jar 包選擇、web.xml 兩種配置方式、核心監聽器原理,適合初次接觸 Spring MVC 的開發者快速上手。

一、準備 Spring Jar 包

  1. 前往 Spring 官網 下載 spring-framework-4.1.x.RELEASE-dist.zip。
  2. 解壓後進入 libs 目錄,核心開發需約 20 個 Jar(含 spring-core、spring-context、spring-web、spring-webmvc、spring-tx、spring-jdbc、spring-orm、spring-aop、spring-expression、aopalliance、commons-logging 等)。
  3. 將所有 Jar 複製至專案 WebContent/WEB-INF/lib(或 Maven 專案的 pom.xml 依賴中)。

二、web.xml 核心配置

Spring 容器啟動靠 ContextLoaderListener,它實現 ServletContextListener,在 Web 應用啟動時初始化 WebApplicationContext。

方式一:約定優於配置(零參數)

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • 預設讀取 /WEB-INF/applicationContext.xml。
  • 檔案名稱、路徑固定,適合極簡專案。

方式二:自定義配置檔路徑(推薦)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-application.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  • classpath: 前綴表示從 src 根目錄尋找,便於多模組專案統一管理配置。
  • 支援多檔案:classpath:spring-dao.xml, classpath:spring-service.xml。

三、Spring 配置檔最小範例

建立 src/spring-application.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"
       xmlns:context="https://www.springframework.org/schema/context"
       xsi:schemaLocation="
           https://www.springframework.org/schema/beans
           https://www.springframework.org/schema/beans/spring-beans.xsd
           https://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 掃描 @Component、@Service、@Repository、@Controller -->
    <context:component-scan base-package="com.example" />

    <!-- 資料源、事務管理等後續再加 -->

</beans>

四、常見坑點提醒

現象原因解決
啟動報 ClassNotFoundException: ContextLoaderListener缺 spring-web.jar補齊 spring-web 依賴
找不到 applicationContext.xml路徑寫錯或未放入 classpath檢查 contextConfigLocation、確認檔案在 src/ 或 WEB-INF/
中文亂碼未配置 CharacterEncodingFilter在 web.xml 最前面加入編碼過濾器

五、驗證整合成功

  1. 啟動 Tomcat,觀察 Console 輸出 Root WebApplicationContext: initialization completed。
  2. 編寫一個 @Controller,瀏覽器訪問對應 URL 返回預期結果。

總結

Spring 整合的核心只有兩步:放 Jar、配 Listener + contextConfigLocation。掌握 ContextLoaderListener 的載入時機與配置檔尋找規則,即可靈活應對各種專案結構。後續可擴展 Spring MVC DispatcherServlet、Hibernate/MyBatis 整合、聲明式事務等進階主題。

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