了解了IOC模式的思想以及其優(yōu)點,再來學習其實現(xiàn)。上篇blog中大致描述了PicoContainer以及Spring各自對IOC的實現(xiàn),這篇來詳細看一下Spring中它的實現(xiàn)。
Spring中IOC貫穿了其整個框架,但正如martinflower所說:“saying that these lightweight containers are special because they use inversion of control is like saying my car is special because it has wheels”,IOC已經稱為框架設計中必不可少的部分。就實現(xiàn)上來講Spring采取了配置文件的形式來實現(xiàn)依賴的注射,并且支持Type2 IOC(Setter Injection)以及Type3 IOC(Constructor Injection)。
Spring中IOC的實現(xiàn)的核心是其Core Bean Factory,它將框架內部的組件以一定的耦合度組裝起來,并對使用它的應用提供一種面向服務的編程模式(SOP:Service-Orient Programming),比如Spring中的AOP、以及持久化(Hibernate、ibatics)的實現(xiàn)。
首先從最底層最基礎的factory Bean開始,先來看org.springframework.beans.factory.Bean
Factory接口,它是一個非常簡單的接口,getBean方法是其中最重要的方法,Spring通常是使用xml來populate Bean,所以比較常用的是XMLFactoryBean。
用一個簡單的示例看一下其用法。首先寫下兩個Bean類:
ExampleBean 類:
public class ExampleBean {
private String psnName=null;
private RefBean refbean=null;
private String addinfo=null;
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 RefBean getRefbean() {
return refbean;
}
public void setAddinfo(String addinfo) {
this.addinfo = addinfo;
}
}
RefBean類:
public class RefBean {
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;
}
private String zipcode=null;
private String address=null;
}
其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>
然后可以寫個測試類來測試,當然,需要Spring中的Spring-core.jar以及commons-logging.jar,當然在elipse中可以通過安裝spring-ide插件來輕松實現(xiàn)。
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)之間的耦合,實現(xiàn)了IOC(控制反轉)或者說實現(xiàn)了依賴的注射(Dependency Injection)。