详解spring-仿springIOC功能的实现
首先解释一下:IOC(控制反转):对象实例的创建不再由应用程序本身创建,而是交由外部容器来创建。
在仿spring框架实现标题所要显示的功能,必须要掌握dom4j解析技术、java反射机制。
通过spring的原理了解,可以明显知道spring框架实现这些功能的步骤是:
1、解析xml文件。2、实例化bean。3、注入bean。
现在我们创建一个beans.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-2.5.xsd">
</beans>
接着我们创建一个PersonDao,所在包路径是com.congine.fire.dao
public interface PersonDao {
public void getInfo();
}
然后再实现这个接口,类名为PersonDaoImpl,所在包路径是com.congine.fire.daoImpl
public class PersonDaoImpl implements PersonDao {
public void getInfo() {
System.out.println("hello world");
}
}
接着就是一个业务bean了,名称为Business,所在包是com.conine.fire.Service
public class Business {
private PersonDao personDao;
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
public void getInfo() {
personDao.getInfo();
}
}
接着我们来配置beans.xml文件增加:
<bean id="personDao" ref="personDao"></property>
</bean>
接着建立跟该xml文件对应的bean如下:
1、建立BeanInformation
private String id;
private String classname;
private List<PropertyInfo> proList = new ArrayList<PropertyInfo>(); 这里之所以建成List是因为需要注入的属性可能有多个。
2、建立PropertyInfo :
private String name;
private String ref;
private String value;
跟spring配置文件中对应的意义一致。
3、建立一个工具类:
public class ClassPathXmlApplicationFire {
private List<BeanInformation> biList = new ArrayList<BeanInformation>();
private Map<String,Object> mapValue = new HashMap<String,Object>();
public ClassPathXmlApplicationFire(String fileName) {
this.parseXml(fileName);//解析配置文件
this.instanceBean();//实例化Bean
this.injectObject();//注入
}
}