首先解释一下:IOC(控制反转):对象实例的创建不再由应用程序本身创建,而是交由外部容器来创建。
在仿spring框架实现标题所要显示的功能,必须要掌握dom4j解析技术、java反射机制。
通过spring的原理了解,可以明显知道spring框架实现这些功能的步骤是:
1、解析xml文件。2、实例化bean。3、注入bean。
现在我们创建一个beans.xml文件。(尚未配置任何bean)
<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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
publicinterfacePersonDao{
publicvoidgetInfo();
}
然后再实现这个接口,类名为PersonDaoImpl,所在包路径是com.congine.fire.daoImpl
publicclassPersonDaoImplimplementsPersonDao{
publicvoidgetInfo(){
System.out.println("helloworld");
}
}
接着就是一个业务bean了,名称为Business,所在包是com.conine.fire.Service
publicclassBusiness{
privatePersonDaopersonDao;
publicvoidsetPersonDao(PersonDaopersonDao){
this.personDao=personDao;
}
publicvoidgetInfo(){
personDao.getInfo();
}
}
接着我们来配置beans.xml文件增加:
<beanid="personDao"class="com.congine.fire.daoImpl.PersonDaoImpl"/>
<beanid="businessService"class="com.congine.fire.busService.BusinessService"
>
<propertyname="personDao"ref="personDao"></property>
</bean>
接着建立跟该xml文件对应的bean如下:
1、建立BeanInformation
privateStringid;
privateStringclassname;
privateList<PropertyInfo>proList=newArrayList<PropertyInfo>();这里之所以建成List是因为需要注入的属性可能有多个。
2、建立PropertyInfo:
privateStringname;
privateStringref;
privateStringvalue;
跟spring配置文件中对应的意义一致。
3、建立一个工具类:
publicclassClassPathXmlApplicationFire{
privateList<BeanInformation>biList=newArrayList<BeanInformation>();
privateMap<String,Object>mapValue=newHashMap<String,Object>();
publicClassPathXmlApplicationFire(StringfileName){
this.parseXml(fileName);//解析配置文件
this.instanceBean();//实例化Bean
this.injectObject();//注入
}
}