简单实现spring中Ioc容器

spring的IOC容器是通过工厂模式+反射机制完成的。

简单来说反射机制就是我们可以通过类的名字来生成对象。

比如比较常见的用法

 Person p=(Person)Class.forName("Chinese").newInstance();

这样子,我们可以直接通过Chinese这个类的名字来构造这个对象。

下面我们看看spring是如何通过IOC来获取对象的。

public class HelloWorld {
   private String message;
   public void setMessage(String message){
    this.message  = message;
   }
   public void getMessage(){
    System.out.println("Your Message : " + message);
   }
}

构造xml文件,定义bean.

<?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-3.0.xsd">

   <bean id="helloWorld" class="com.HelloWorld">
       <property name="message" value="Hello World!"/>
   </bean>

</beans>

通过BeanFactory来获取对象实例。

public class MainApp {
   public static void main(String[] args) {
      XmlBeanFactory factory = new XmlBeanFactory
                             (new ClassPathResource("Beans.xml"));
      HelloWorld obj = (HelloWorld) factory.getBean("helloWorld");
      obj.getMessage();
   }
}

可见它的原理是这样子的,通过解析xml文件,获取类的名称。

通过反射机制,生成对象并且返回。

下面我们简单实现一下。

public interface Person {
   public void say();
}

Chinese继承于Person接口。

扫描二维码关注公众号,回复: 2429898 查看本文章
public class Chinese implements Person{
    private String name="huang";
    private int age=22;

    public void say(){
        System.out.println(name+" "+age);
    }
}

最后我们写一个工厂模式来输出实例。

public class BeanFactory {

    public static Person getInstance(String classname){
        Person p=null;
        try {
            p=(Person)Class.forName(classname).newInstance();
        }catch (Exception e){
            e.printStackTrace();
        }
        return  p;
    }


}

实验一下:

public class Test {

    public static void main(String[] args){
        Person p=BeanFactory.getInstance("Chinese");
        p.say();

    }

输出是 huang 22

总结:

    通过反射机制,可以用很少的代码去实例化所以的类,而且不需要程序员再去改动BeanFactory方法。

    反之没有反射机制的话,我们每写一个类比如England类,那我们就要重新修改BeanFactory了,非常麻烦









猜你喜欢

转载自blog.csdn.net/qq_34761108/article/details/79476525