浅谈Spring IOC与DI原理Word下载.docx
《浅谈Spring IOC与DI原理Word下载.docx》由会员分享,可在线阅读,更多相关《浅谈Spring IOC与DI原理Word下载.docx(14页珍藏版)》请在冰点文库上搜索。
A需要依赖Connection才能正常运行,而这个Connection是由spring注入到A中的,依赖注入的名字就这么来的。
那么DI是如何实现的呢?
Java1.3之后一个重要特征是反射(reflection),它允许程序在运行的时候动态的生成对象、执行对象的方法、改变对象的属性,spring就是通过反射来实现注入的。
关于反射的相关资料请查阅javadoc。
理解了IoC和DI的概念后,一切都将变得简单明了,剩下的工作只是在spring的框架中堆积木而已。
如果还不明白,放弃java吧!
下面来让大家了解一下Spring到底是怎么运行的。
Java代码
publicstaticvoidmain(String[]args){
ApplicationContextcontext=newFileSystemXmlApplicationContext(
"
applicationContext.xml"
);
Animalanimal=(Animal)context.getBean("
animal"
animal.say();
}
publicstaticvoidmain(String[]args){
ApplicationContextcontext=newFileSystemXmlApplicationContext(
}
这段代码你一定很熟悉吧,不过还是让我们分析一下它吧,首先是applicationContext.xml
<
beanid="
class="
phz.springframework.test.Cat"
>
propertyname="
name"
value="
kitty"
/>
/bean>
<
他有一个类phz.springframework.test.Cat
publicclassCatimplementsAnimal{
privateStringname;
publicvoidsay(){
System.out.println("
Iam"
+name+"
!
"
publicvoidsetName(Stringname){
this.name=name;
publicclassCatimplementsAnimal{
publicvoidsay(){
publicvoidsetName(Stringname){
}
实现了phz.springframework.test.Animal接口
publicinterfaceAnimal{
publicvoidsay();
publicinterfaceAnimal{
很明显上面的代码输出Iamkitty!
那么到底Spring是如何做到的呢?
接下来就让我们自己写个Spring来看看Spring到底是怎么运行的吧!
首先,我们定义一个Bean类,这个类用来存放一个Bean拥有的属性
/*BeanId*/
privateStringid;
/*BeanClass*/
privateStringtype;
/*BeanProperty*/
privateMap<
String,Object>
properties=newHashMap<
();
/*BeanId*/
/*BeanClass*/
/*BeanProperty*/
一个Bean包括id,type,和Properties。
接下来Spring就开始加载我们的配置文件了,将我们配置的信息保存在一个HashMap中,HashMap的key就是Bean的Id,HasMap的value是这个Bean,只有这样我们才能通过context.getBean("
)这个方法获得Animal这个类。
我们都知道Spirng可以注入基本类型,而且可以注入像List,Map这样的类型,接下来就让我们以Map为例看看Spring是怎么保存的吧
Map配置可以像下面的
test"
Test"
testMap"
map>
entrykey="
a"
value>
1<
/value>
/entry>
b"
2<
/map>
/property>
Spring是怎样保存上面的配置呢?
,代码如下:
if(beanProperty.element("
map"
)!
=null){
Map<
propertiesMap=newHashMap<
ElementpropertiesListMap=(Element)beanProperty
.elements().get(0);
Iterator<
?
propertiesIterator=propertiesListMap
.elements().iterator();
while(propertiesIterator.hasNext()){
Elementvet=(Element)propertiesIterator.next();
if(vet.getName().equals("
entry"
)){
Stringkey=vet.attributeValue("
key"
valuesIterator=vet.elements()
.iterator();
while(valuesIterator.hasNext()){
Elementvalue=(Element)valuesIterator.next();
if(value.getName().equals("
value"
propertiesMap.put(key,value.getText());
ref"
propertiesMap.put(key,newString[]{value
.attributeValue("
bean"
)});
bean.getProperties().put(name,propertiesMap);
if(beanProperty.element("
=null){
ElementpropertiesListMap=(Element)beanProperty
propertiesIterator=propertiesListMap
while(propertiesIterator.hasNext()){
)){
valuesIterator=vet.elements()
while(valuesIterator.hasNext()){
propertiesMap.put(key,newString[]{value
接下来就进入最核心部分了,让我们看看Spring到底是怎么依赖注入的吧,其实依赖注入的思想也很简单,它是通过反射机制实现的,在实例化一个类时,它通过反射调用类中set方法将事先保存在HashMap中的类属性注入到类中。
让我们看看具体它是怎么做的吧。
首先实例化一个类,像这样
publicstaticObjectnewInstance(StringclassName){
Class<
cls=null;
Objectobj=null;
try{
cls=Class.forName(className);
obj=cls.newInstance();
}catch(ClassNotFoundExceptione){
thrownewRuntimeException(e);
}catch(InstantiationExceptione){
}catch(IllegalAccessExceptione){
returnobj;
publicstaticObjectnewInstance(StringclassName){
try{
}catch(ClassNotFoundExceptione){
}catch(InstantiationExceptione){
}catch(IllegalAccessExceptione){
接着它将这个类的依赖注入进去,像这样
publicstaticvoidsetProperty(Objectobj,Stringname,Stringvalue){
extendsObject>
clazz=obj.getClass();
StringmethodName=returnSetMthodName(name);
Method[]ms=clazz.getMethods();
for(Methodm:
ms){
if(m.getName().equals(methodName)){
if(m.getParameterTypes().length==1){
clazzParameterType=m.getParameterTypes()[0];
setFieldValue(clazzParameterType.getName(),value,m,
obj);
break;
}catch(SecurityExceptione){
}catch(IllegalArgumentExceptione){
}catch(InvocationTargetExceptione){
publicstaticvoidsetProperty(Objectobj,Stringname,Stringvalue){
ms){
if(m.getName().equals(methodName)){
if(m.getParameterTypes().length==1){
setFieldValue(clazzParameterType.getName(),value,m,
}catch(SecurityExceptione){
}catch(IllegalArgumentExceptione){
}catch(InvocationTargetExceptione){
最后它将这个类的实例返回给我们,我们就可以用了。
我们还是以Map为例看看它是怎么做的,我写的代码里面是创建一个HashMap并把该HashMap注入到需要注入的类中,像这样,
if(valueinstanceofMap){
entryIterator=((Map<
?
)value).entrySet()
map=newHashMap<
while(entryIterator.hasNext()){
Entry<
entryMap=(Entry<
)entryIterator.next();
if(entryMap.getValue()instanceofString[]){
map.put((String)entryMap.getKey(),
getBean(((String[])entryMap.getValue())[0]));
BeanProcesser.setProperty(obj,property,map);
if(valueinstanceofMap){
)value).entrySet()
while(entryIterator.hasNext()){
if(entryMap.getValue()instanceofString[]){
map.put((String)entryMap.getKey(),
好了,这样我们就可以用Spring给我们创建的类了,是不是也不是很难啊?
当然Spring能做到的远不止这些,这个示例程序仅仅提供了Spring最核心的依赖注入功能中的一部分。