一、下載 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. 運行主程序,結果如下:
