注:僅僅是個人學習總結的筆記,例子來自于《
Spring
技術手冊》、《
Expert One-On-One J2EE Development Without EJB
中文版》、以及一些網絡文檔等。
?
1.??????
準備工作
從下載的
spring
開發包
bin
目錄下將相關
lib
加入至項目的
ClassPath
中。
我加入的
lib
文件有:
spring.jar
(這個文件包括了所有
Spring
支持的功能所需要的類,而不再需要加入個別的
jar
文件,關于
Spring
各個具體的
jar
包的使用范圍,可查詢
Spring
的中文文檔)
commons-logging.jar
;
log4j.jar
(
log
日志所需)
?
編寫
log4j
配置文件
log4j.properties
,將其放入
src
下,
log4j.properties
內容如下:
log4j.rootLogger=
ERROR,
stdout
?
log4j.appender.stdout=
org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=
org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=
%c
{1}
-
%m%n
?
我的工程目錄結構如下:
????SpringProject(工程名稱)
?????? src
????????? log4j.properties
?????? lib
????????? commons-logging.jar
????????? log4j-1.2.9.jar
??????????spring.jar
??????????
2.??????
編寫第一個
Spring
程序
這是一個簡單的
JavaBean
,用來打聲招呼。
?
●????
HelloBean.java
package com.kela.spring.helloword;
?
public class HelloBean {
??????
?????? private String helloWord;
?????? public String getHelloWord() {
????????????? return helloWord;
?????? }
?????? public void setHelloWord(String helloWord) {
????????????? this.helloWord = helloWord;
?????? }
}
●????
beans-config.xml
?
<?xml
version=
"1.0"
encoding=
"GB2312"
?>
<!DOCTYPE
beans
PUBLIC
"-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd"
>
???
<beans>
?????
<bean
id=
"helloBean"
class=
"com.kela.spring.helloword.HelloBean"
>
??????
???
<property
name=
"helloWord"
>
??????????
???
<value>
你好,
Spring
愛好者!
</value>
??????
???
</property>
???
???
</bean>
</beans>
●????
TestClass.java
?
??? package com.kela.spring.helloword;
?
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
?
public class TestClass {
?
??????
??? public static void main(String[] args) {
?????????????
??? try {
????????????????????
??? ApplicationContext context = new
FileSystemXmlApplicationContext("bin\\com\\kela\\spring\\helloword\\beans-config.xml");
????????????????????
????????????????????
??? HelloBean helloBean = (HelloBean)context.getBean("helloBean");
????????????????????
????????????????????
??? System.out.println("
打印歡迎詞:
" + helloBean.getHelloWord());
?????????????
??? } catch (Exception e) {
????????????????????
??? System.out.println("[ERROR]" + e.getMessage());
?????????????
??? }
??????
??? }
}
3.??????
測試
?
運行
TestClass.java
文件,內容如下:
打印歡迎詞:你好,
Spring
愛好者!
4.???????
學習小結
?
通過配置的形式,對
HelloBean.java
文件中屬性
helloWord
注入了一段文件(你好,
spring
愛好者),
HelloBean.java
文件中沒有任何與
Spring
有關的東西,在測試類中對
HelloBean
的聲明是由
Spring
自動完成的。