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

SSH 整合實戰(一):Eclipse + Tomcat 搭建 Spring 2.5 基礎環境

     編輯:Java 相關知識

系列首篇,從零開始在 Eclipse 3.4(原版)+ Tomcat 5.5 中創建 Dynamic Web Project,配置 Spring 2.5 核心容器,驗證 IoC 依賴注入是否生效。作者分享選擇 Eclipse 而非 MyEclipse/NetBeans 的心路歷程,強調初學者應避免過度依賴可視化工具。

項目創建

  1. New → Project → Web → Dynamic Web Project。
  2. 項目名 miziStudy,Target Runtime 選 Tomcat 5.5。
  3. Finish 使用默認結構(src、WebContent、WEB-INF/lib 等)。

web.xml 配置 Spring 容器啟動

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

classpath: 前綴表示從類路徑(src 或 WEB-INF/classes)加載,支持通配符批量載入。

Spring 配置文件 (src/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"
  xmlns:p="https://www.springframework.org/schema/p"
  xmlns:aop="https://www.springframework.org/schema/aop"
  xmlns:tx="https://www.springframework.org/schema/tx"
  xsi:schemaLocation="https://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    https://www.springframework.org/schema/aop
    https://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    https://www.springframework.org/schema/tx
    https://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
</beans>

注意:Schema 版本必須與 Jar 包一致(2.5),混用 2.0 會導致加載失敗。

核心 Jar 包 (WEB-INF/lib)

  • spring.jar(或拆分的 spring-core、spring-beans、spring-context、spring-aop、spring-tx、spring-web 等)
  • commons-logging.jar
  • log4j.jar(可選,配合 log4j.properties 放類路徑)

驗證 IoC 注入

POJO 類

package spring.test.hello;
public class UserPo {
    private String username, sex; private int age;
    // getter/setter 省略
}

測試類

public class HelloTest {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserPo user = (UserPo) ac.getBean("UserPo");
        System.out.println("Hello:" + user.getUsername() + ";u is " + user.getAge() + " age; and u is a " + user.getSex());
    }
}

注入配置

<bean id="UserPo" class="spring.test.hello.UserPo">
  <property name="username" value="Mizi"/>
  <property name="age" value="25"/>
  <property name="sex" value="man"/>
</bean>

運行與結果

右鍵 HelloTest.java → Run As → Java Application。Console 輸出:
Hello:Mizi;u is 25 age; and u is a man
即表明 Spring 容器啟動、Bean 實例化、屬性注入全部正常。

初學者建議

  • 優先理解 XML 配置與 Java 代碼的對應關係,再使用註解/自動掃描。
  • 保持 Jar 版本統一,避免「Jar 地獄」。
  • Eclipse 內置 Tomcat 插件調試比外部部署效率高得多。
  • 源碼下載鏈接:配套源碼
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved