系列首篇,從零開始在 Eclipse 3.4(原版)+ Tomcat 5.5 中創建 Dynamic Web Project,配置 Spring 2.5 核心容器,驗證 IoC 依賴注入是否生效。作者分享選擇 Eclipse 而非 MyEclipse/NetBeans 的心路歷程,強調初學者應避免過度依賴可視化工具。
miziStudy,Target Runtime 選 Tomcat 5.5。<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)加載,支持通配符批量載入。
<?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 會導致加載失敗。
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 實例化、屬性注入全部正常。