Spring是一個開源的控制反轉(IOC)和麪向反切(AOP)的容器框架,主要用於簡化企業開發,可以適用於任何java應用程序。使用框架的主要優勢在於其分層架構,分層架構允許選擇使用哪一個組件,同時爲 J2EE 應用程序開發提供集成的框架。
2.優點:
1 降低組件之間的耦合度,實現軟件各層之間的解耦。
2 可以使用容器提供衆多的服務(事務管理服務、消息服務)。
3 容器提供單例模式支持,開發人員不再需要自己編寫實現代碼。
4 容器提供了AOP技術,利用它很容易實現如權限攔截,運行期監控等功能。
5 容器提供衆多輔作類,使用這些類能夠加快應用的開發。
6 Spring對於主流的應用框架提供了集成支持,便於應用開發。
3.模塊組成:
1 核心容器:提供Spring框架的基本功能,BeanFactory是其主要組件,它是工廠
模式的實現。BeanFactory使用控制反轉模式將應用程序的配置和依賴性規範與實
際的應用程序代碼分開。
2 Spring上下文:是一個配置文件,向Spring框架提供上下文信息。
3 Spring AOP:直接將面向方面的編程功能集成到Spring框架中,爲基於Spring的
應用程序中的對象提供了事務管理服務。
4 Spring DAO:提供了異常層次結構,可用該結構來管理異常處理和不同數據庫
供應商給定的錯誤信息。簡化了錯誤處理,且大大降低了需要編寫的異常代碼數
量。
5 Spring ORM:提供ORM的對象關係工具,遵從Spring的通用事務和DAO異常層次
結構。
6 Spring Web:建立在應用程序上下文模塊之上,爲基於Web的應用程序提供了上
下文,簡化了處理多部分請求以及將請求參數綁定到域對象的工作。
7 Spring MVC:是一個全功能的構建Web應用程序的MVC實現。
Spring模塊構建在覈心容器之上,核心容器定義了創建、配置和管理bean的方
式。每個模塊都可以單獨存在,也可以與其他模塊聯合實現。
不經意找到一個很不錯的例子來說明Spring框架的作用:
首先寫下兩個Bean類:
ExampleBean類:
public class ExampleBean {
private String psnName=null;
private RefBean refbean=null;
private String addinfo=null;
public RefBean getRefbean() {
return refbean;
}
public String getAddinfo() {
return getRefbean().getAddress()+getRefbean().getZipcode();
}
public String getPsnName() {
return psnName;
}
public void setPsnName(String psnName) {
this.psnName = psnName;
}
public void setRefbean(RefBean refbean) {
this.refbean = refbean;
}
public void setAddinfo(String addinfo) {
this.addinfo = addinfo;
}
}
RefBean類:
public class RefBean {
private String zipcode=null;
private String address=null;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
}
其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="exampleBean" class="test.ExampleBean">
<property name="psnName"><value>xkf</value></property>
<property name="refbean">
<ref bean="refBean"/>
</property>
</bean>
<bean id="refBean" class="test.RefBean">
<property name="address"><value>BeiJing</value></property>
<property name="zipcode"><value>100085</value></property>
</bean>
</beans>
測試類Test:
public class Test {
public static void main(String[] args){
try{
Resource input = new ClassPathResource("test/Bean.xml");
System.out.println("resource is:"+input);
BeanFactory factory = new XmlBeanFactory(input);
ExampleBean eb =
(ExampleBean)factory.getBean("exampleBean");
System.out.println(eb.getPsnName());
System.out.println(eb.getAddinfo());
}
catch(Exception e){
e.printStackTrace();
}
}
這樣,通過BeanFactory的getBean方法,以及xml配置文件,避免了在test類中直接實例化ExampleBean,消除了應用程序(Test)與服務(ExampleBean)之間的耦合,實現了IOC(控制反轉)或者說依賴的注射(Dependency Injection)。