1. 程式人生 > >Spring基礎(一)之Spring概述

Spring基礎(一)之Spring概述

Spring框架主要由7大模組組成,每個模組都可以單獨使用,也可以和其他模組組合使用。

(1)Spring Core模組

該模組是Spring的核心容器,它實現了IoC模式和Spring框架的基礎功能。在模組中最重要的BeanFactory類是Spring的核心類,負責配置與管理JavaBean。它採用Factory模式實現了IoC容器,及依賴注入。

(2)Context模組

該模組繼承BeanFactory類,並且添加了事件處理、國際化、資源載入、透明載入,以及資料校驗等功能。他還提供了框架式的Bean的訪問方式和很多企業級的功能,如JNDI訪問、支援EJB、繼承模板框架、Email和定時任務排程等。

(3)AOP模組

Spring集成了所有AOP功能,通過事務管理可以將任意Spring管理的物件AOP化。Spring提供了用標準java語言編寫的AOp框架。

(4)DAO模組

該模組技工了JDBC的抽象層,簡化了資料庫廠商的異常錯誤,大幅度減少了程式碼的編寫並且提供了對宣告式和編寫式事物的支援。

(5)O/R對映模組

該模組提供了對現有ORM框架的支援,各種流行的ORM框架已經非常成熟如:hibernate,Spring沒有必要開發新的ORM工具,但是為Hibernate提供了完美的整合功能,並且支援其他ORM工具。

(6)Web模組

該模組建立在Spring Context基礎之上,提供了Servlet監聽器的Context和Web應用的上下文,為現有的Web框架如JSF、Taperstry和Struts等提供了整合。

(7)MVC模組

該模組建立在Spring核心功能之上,使其擁有Spring框架的所有特性。從而能夠適應多種多檢視、模板技術、國際化和驗證服務,實現控制邏輯和業務邏輯的清晰分離。

下面用Spring開發一個簡單的例項:

1)新建一個工程取名為:HelloWorld。然後將Spring的包匯入到WebRoot/Web-INF/lib下。

2)編寫一個簡單的Bean類 放到src資料夾下eg:

package edu.xaut.jzd.spring;

public class HelloWorld {
private String greeting;

public String getGreeting() {
return "hello "+greeting;
}


public void setGreeting(String greeting) {
this.greeting = greeting;
System.out.println("設定greeting屬性");
}

}

3)使用Spring的xml配置檔案來建立HelloWorld 類的物件例項(也稱為裝配Bean)。在src下新建一個applicationContext.xm檔案。eg:

?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
       <bean id="helloworld" class="edu.xaut.jzd.spring.HelloWorld">
       <property name="greeting" >
       <value>xautjzd</value>
       </property>
       </bean>
</beans>

4)編寫一個HelloWordTest類來測試裝配的Bean。為了使用裝配的Bean,需要使用ApplicationContext物件。eg:

package edu.xaut.jzd.spring;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;


public class HelloWorldTest {
public static void main(String[] args){
//裝配applicationContext.xml檔案
ApplicationContext context =new FileSystemXmlApplicationContext("src\\applicationContext.xml");
//獲得被裝配的HelloWorld物件例項
HelloWorld helloWorld = (HelloWorld)context.getBean("helloworld");
System.out.println(helloWorld.getGreeting());
}
}

到此,一個簡單的例項就完成了,由於我用的是spring3.1.1,執行後會出現如下錯誤:

Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/common

原因是沒有載入commons-logging包,此包在struts的lib包裡面有,載入到專案中即可。