計劃用一個月時間來學習Spring,在這里把自己的學習過程記錄下來,方便想學習Spring的人,也為自己日后復習有個參考。以下通過一個簡單的例子來先了解下Spring的用法。
(1)創建一個java工程,建立如下類:HelloBean
package com.ducklyl;
public class HelloBean {
private String helloWord;
public String getHelloWord() {
return helloWord;
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
}
(2)創建Spring配置文件:beans-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="helloBean" class="com.ducklyl.HelloBean">
<property name="helloWord">
<value>Hello,ducklyl!</value>
</property>
</bean>
</beans>
(3)導入Spring所需的包:commons-logging.jar,spring.jar 。(日志包和Spring包)
包下載地址:
http://www.ziddu.com/download/3555993/Spring.rar.html
(4)創建測試類:SpringDemo.java
package com.ducklyl;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.*;
public class SpringDemo{
public static void main(String[] args)
{
//讀取配置文件
Resource rs=new FileSystemResource("beans-config.xml");
//實例化Bean工廠
BeanFactory factory=new XmlBeanFactory(rs);
//獲取id="helloBean"對象
HelloBean hello=(HelloBean)factory.getBean("helloBean");
//調用helloBean對象getHelloWord()方法
System.out.println(hello.getHelloWord());
}
}
如果以上配置正確的話,運行SpringDemo.java,可以看到輸出結果:Hello,ducklyl!