Spring框架
1.1:了解Spring
Spring的核心是提供了一个容器,主要通过 BeanFactory(接口)来创建和管理对象,一般我们用它的子类ApplicationContext
来创建和管理对象。(核心技术就是IOC(控制反转))
1.spring的IOC容器能够帮我们自动new对象,对象交给spring管之后我们不用自己手动去new对象了。
那么它的原理是什么呢?是怎么实现的呢?下面我来简单的模拟一下spring的机制,相信看完之后就会对spring的原理有一定的了解。
2.spring使用BeanFactory来实例化、配置和管理对象,但是它只是一个接口,里面有一个getBean()方法。
我们一般都不直接用BeanFactory,而是用它的实现类ApplicationContext,这个类会自动解析我们配置的applicationContext.xml,
然后根据我们配置的bean来new对象,将new好的对象放进一个Map中,键就是我们bean的id,值就是new的对象。
具体操作:
step1.首先我们建立一个BeanFactory接口
package com.spring; public interface BeanFactory { Object getBean(String id); }
step2.然后建立一个BeanFactory的实现类ClassPathXmlApplicationContext.java
package com.spring; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class ClassPathXmlApplicationContext implements BeanFactory { private Map<String, Object> beans = new HashMap<String, Object>(); public ClassPathXmlApplicationContext(String fileName) throws Exception{ SAXReader reader = new SAXReader(); Document document = reader.read(this.getClass().getClassLoader().getResourceAsStream(fileName)); List<Element> elements = document.selectNodes("/beans/bean"); for (Element e : elements) { String id = e.attributeValue("id"); String value = e.attributeValue("class"); Object o = Class.forName(value).newInstance(); beans.put(id, o); } } public Object getBean(String id) { return beans.get(id); } }
step3.然后配置applicationContext.xml---名字
<?xml version="1.0" encoding="UTF-8"?> <beans> <bean id="c" class="com.spring.Car"></bean> <bean id="p" class="com.spring.Plane"></bean> </beans>
step4.创建接口,顺便演示工厂模式
package com.spring; public interface Moveable { void run(); } --汽车类,实现接口 package com.spring; public class Car implements Moveable{ public void run(){ System.out.println("拖着四个轮子满街跑car·····"); } } ---飞机类,实现接口 package com.spring; public class Plane implements Moveable{ public void run() { System.out.println("拖着翅膀天空飞plane......"); } }
step5.现在来看一看效果吧,写一个类测试一下:
package com.spring; import org.dom4j.DocumentException; public class Test { /** * @param args * @throws DocumentException */ public static void main(String[] args) throws Exception { BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml"); Object o = factory.getBean("c"); Moveable m = (Moveable)o; m.run(); } }