一、準備工作
下載SpringFramework的最新版本,并解壓縮到指定目錄。
在IDE中新建一個項目,并將Spring.jar將其相關類庫加入項目。
二、構建 Spring 基礎代碼
1. Action接口:
Action 接口定義了一個 execute 方法
execute方法,以完成目標邏輯。
public interface Action {
public String execute(String str);
}
2. Action接口的兩個實現UpperAction、LowerAction
public class UpperAction implements Action {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String string) {
message = string;
}
public String execute(String str) {
return (getMessage() + str).toUpperCase();
}
}
UpperAction將其message屬性與輸入字符串相連接,并返回其大寫形式。
SpringFrameWork Developer’s Guide Version 0.6
October 8, 2004 So many open source projects. Why not Open your Documents?
public String getMessage() {
return message;
}
public void setMessage(String string) {
message = string;
}
public String execute(String str) {
return (getMessage()+str).toLowerCase();
}
}
LowerAction將其message屬性與輸入字符串相連接,并返回其小寫形式。
3. Spring配置文件(bean.xml)
<beans>
<description>Spring Quick Start</description>
<bean id="TheAction"
class="net.xiaxin.spring.qs.UpperAction">
<property name="message">
<value>HeLLo</value>
</property>
</bean>
</beans>
(請確保配置bean.xml位于工作路徑之下,注意工作路徑并不等同于CLASSPATH ,eclipse
的默認工作路徑為項目根路徑,也就是.project文件所在的目錄,而默認輸出目錄/bin是項目
CLASSPATH的一部分,并非工作路徑。 )
4. 測試代碼
public void testQuickStart() {
ApplicationContext ctx=new
FileSystemXmlApplicationContext("bean.xml");
Action action = (Action) ctx.getBean("TheAction");
System.out.println(action.execute("Rod Johnson"));
}
可以看到,上面的測試代碼中,我們根據"bean.xml"創建了一個ApplicationContext實
例,并從此實例中獲取我們所需的Action實現。
SpringFrameWork Developer’s Guide Version 0.6
October 8, 2004 So many open source projects. Why not Open your Documents?
運行測試代碼,我們看到控制臺輸出:
……
HELLO ROD JOHNSON
我們將bean.xml中的配置稍加修改:
<bean id="TheAction"
class="net.xiaxin.spring.qs.LowerAction"/>
再次運行測試代碼,看到:
……
hello rod johnson
示例完成!
很簡單的示例!從這個示例呢,可以簡單的了解Spring的基本構造。但是,看完這些,還不明白Spring的好處。
下一篇文章將就我的理解談談Sping的好處。
posted on 2009-03-23 09:48
重慶理工小子 閱讀(2341)
評論(0) 編輯 收藏 所屬分類:
Spring2