解析Spring IOC原理——工厂模式与反射机制的综合应用

spring IOC的原理

首先我们来讲下为什么要引入IOC:

假设上面举例的那个程序已经部署到服务器中,并已经上线运行,这时项目来了这样一个新需求:增加一个Japanese类,并且在HelloWorldTest 类中调用Japanese的sayHelloWorld方法。在没有引入IOC之前,很显然我们为了这个新需求,必须把项目停止下来,然后从新编译HumanFactory 和HelloWorldTest这两个类,最后再重新上线运行。

而使用IOC,则能够在不重新编译部署的情况下实现上面的新需求!

那么我们来看一下IOC是去怎么实现这个新需求的: 

 首先我们在com.human包内创建一个Japanese类:

public class Japanese implements Human{  
     private String name;  
     private String age;  
       
     public void sayHelloWorld(String string){  
         System.out.println("你好,"+string);  
     }  
     public String getAge() {  
     return age;  
     }  
     public void setAge(String age) {  
     this.age = age;  
     }  
     public String getName() {  
     return name;  
     }  
     public void setName(String name) {  
         this.name = name;  
     }  
}  

然后对HelloWorldTest 类做如下修改

public class HelloWorldTest {  
  
       public static void main(String[] args) {  
             ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");  
             BeanFactory beanFactory=ctx.getBeanFactory();  
             Human human=beanFactory.getBean("human");  
             human.sayHelloWorld("极度暴走");  
             }  
}  

然后我们在beans.xml中做如下配置:

<?xml version="1.0" encoding="UTF-8"?>  
  
<beans>  
    <bean id="human" class="com.human.Japanese">  
       <property name="name">  
           <value>漩涡鸣人</value>  
       </property>  
       <property name="password">  
           <value>22</value>  
       </property>  
<pre class="html" name="code"></bean>  
</beans>

这样,HelloWorldTest 便会去调用Japanese类的sayHelloWorld()方法;用这种形式,我们只要修改beans.xml的配置便可以改变HelloWorldTest 类中human对象,并且不需要重新部署项目,这样就实现了human对象的热拔插。</p>  

总结:从上面的代码可以看出Spring的bean工厂主要实现了以下几个步骤
1.解析配置文件(bean.xml)
2.使用反射机制动态加载每个class节点中配置的类 
3.为每个class节点中配置的类实例化一个对象
4.使用反射机制调用各个对象的seter方法,将配置文件中的属性值设置进对应的对象
5.将这些对象放在一个存储空间(beanMap)中</p>  
6.使用getBean方法从存储空间(beanMap)中取出指定的JavaBean 
PS:IOC的标准定义:
(Inversion of Control) 
中文译为: 控制反转
IOC的基本概念是:不创建对象,但是描述创建它们的方式。在代码中不直接与对象和服务连接,但在配置文件中描述哪一个组件需要哪一项服务。容器负责将这些联系在一起。

猜你喜欢

转载自blog.csdn.net/u010310183/article/details/83750360