地址: https://github.com/zhuchangwu/CIOC
项目中有两种方式实现IOC:
singletonObjects
的CurrentHashMap
singletonFactories
类型:CurrentHashMap
beanDefinitionMap
类型:CurrentHashMap
Spring底层的自己还封装了BeanDefinition, 当然我没干这件事,直接用的类的描述对象 Class
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CDao {
String value()default "";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface CService {
String value()default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface CComponentScan {
String value()default "";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CAutowired {
String value()default "";
}
在我手动写如何解决循环依赖的时候,那时候我还没有去看源码, 当时我画了几个流程图,但是还是卡壳了, 于是我去调试Spring的实现, 简直了!Spring的作者们简直是真神!
其实说Spring如何解决循环依赖的,我前面有几个源码阅读的博客,感兴趣可以去看看
这里我就简单的说下, 这件事是一个叫 AutowiredAnnotationBeanDefinitonPostprocessor
的后置处理器完成的, Spring在做这件事是时候,前前后后是一个偌大的继承体系在支持, 但是归根结底是Spring玩了个漂亮的递归,方法名是getBean(),当然这个递归还有几个辅助容器,这几个容器就是我上面说的几个map ,我的IOC能写成,就得益于这一点
注解版的IOC我是用DOM4j解析XML配置文件实现的, 做了下面的功能
标识性的信息是 property
<bean id="dao1" class="com.changwu.dao.DaoImpl1"></bean>
<bean id="service" class="com.changwu.service.UserServiceImpl4">
<property ref="dao1" name="daoImpl"></property>
</bean>
标识性的信息是 constructor-arg
<bean id="DaoImpl" class="com.changwu.dao.DaoImpl1"></bean>
<bean id="service" class="com.changwu.service.UserServiceImpl3">
<constructor-arg ref ="DaoImpl" name="DaoImpl1"></constructor-arg>
</bean>
</bean>
标识性的信息是 byType
<beans default-autowire="byType">
<beans default-autowire="byName">
地址: https://github.com/zhuchangwu/CIOC