eclipse中匯入spring詳細過程
spring簡介
Spring是一個開源框架,Spring是於2003 年興起的一個輕量級的Java 開發框架,由Rod Johnson建立。簡單來說,Spring是一個分層的JavaSE/EEfull-stack(一站式) 輕量級開源框架。
eclipse中匯入spring
在匯入spring之前先要下載spring-framework-x.xx.RELEASE下載地址:springframework 如果jdk版本在1.7或者以下的最好下載3.x.x.RELEASE的版本,我下載的為spring-framework-3.2.9.RELEASE的版本,下載完spring-framework-3.2.9.RELEASE之後,還要下載一個Commons Logging.zip檔案下載地址
上面是匯入後項目的圖。
spring的簡單使用
上面已經將spring框架匯入到了我們當前的專案中,現在來一個小小的demo體驗一下spring的用法。先看一下專案的框架:
在src資料夾下新建一個springTest類和一個PersonService類,
//PersonService 類
public class PersonService {
private String name;
public void setName(String name) {
this.name = name;
}
public void info () {
System.out.println("此人名字為:"+name);
}
}
//springTest 類
package springdemo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("bean.xml");
System.out.println(ctx);
PersonService p=ctx.getBean("PersonService", PersonService.class);
p.info();
}
}
在src資料夾下新建一個bean.xml檔案,一定要注意是在src資料夾下,不要將bean.xml的位置放錯了不然程式執行會出現異常。
//bean.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="PersonService" class="springdemo.PersonService">
<property name="name" value="hanking">
</property>
</bean>
</beans>
到現在為止一切就緒,點選執行:
//輸出
org.springframework.context.support.ClassPathXmlApplicationContext@2635ee49: startup date [Tue May 16 15:32:21 CST 2017]; root of context hierarchy
此人名字為:hanking
好了一個小小的spring專案就完成了。