Spring 的下載、安裝和使用

中國風2012發表於2014-07-16

一、下載 Spring 下載地址:http://repo.spring.io/libs-release-local/org/springframework/spring/4.0.6.RELEASE/    下載zip壓縮包:  spring-framework-4.0.6.RELEASE-dist.zip 並解壓。

 

二、在 Eclipse 呀 myEclipse 中開發 Spring 應用

 

  1. 新建 java project  專案命名為 myspring

  2. 為該專案增加 Spring 支援。新增使用者庫 spring4.0.6 和 common-logging 新增方法如下圖:



commons-logging-1.1.3.jar


  3. 定義一個 Spring 管理容器中的 Bean  (POJO)  src\hsl\service\PersonService.java 程式碼如下: 

package hsl.service;

public class PersonService {
	private String name;

	// name屬性的setter方法
	public void setName(String name) {
		this.name = name;
	}

	// 測試Person類的info方法
	public void info() {
		System.out.println("此人名為:" + name);
	}
}

注:Spring 可以管理任意的 POJO,並不要求 java 類是一個標準的 JavaBean.

  4. 編寫主程式,該程式初始化 Spring 容器 src\hsl\SpringTest.java  程式碼如下:

package hsl;

import hsl.service.PersonService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
	public static void main(String[] args) {
		// 建立Spring的ApplicationContext
		ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");
		System.out.println(ctx); // 輸出Spring容器

		// 通過 Spring 容器獲取 Person 例項,併為 Person 例項設定屬性值(這種方式稱為控制反轉,IoC)
		PersonService p = ctx.getBean("personService", PersonService.class);
		p.info();
	}
}

  5. 將 PersionService 類部署在 Spring 配置檔案中, src\bean.xml  程式碼如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<!-- 將PersonService類部署成Spring容器中的Bean  -->
	<bean id="personService" class="hsl.service.PersonService">
		<property name="name" value="wawa"/>
	</bean>
</beans>

  6. 執行主程式,結果如下:

 


 

 

 

 

 

 

相關文章