了解了IOC模式的思想以及其优点,再来学习其实现。上篇blog中大致描述了PicoContainer以及Spring各自对IOC的实现,这篇来详细看一下Spring中它的实现。
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已经称为框架设计中必不可少的部分。就实现上来讲Spring采取了配置文件的形式来实现依赖的注射,并且支持Type2 IOC(Setter Injection)以及Type3 IOC(Constructor Injection)。
Spring中IOC的实现的核心是其Core Bean Factory,它将框架内部的组件以一定的耦合度组装起来,并对使用它的应用提供一种面向服务的编程模式(SOP:Service-Orient Programming),比如Spring中的AOP、以及持久化(Hibernate、ibatics)的实现。
首先从最底层最基础的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插件来轻松实现。
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)。本文地址:http://com.8s8s.com/it/it13818.htm