ClassPathResource res = new ClassPathResource("beans.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
reader.loadBeanDefinitions(res);
User user=(User) factory.getBean("user");
spring源码解析
所以我们先从DefaultListableBeanFactory开始了解
AbstractBeanFactory
public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
return doGetBean(name, requiredType, args, false);
}
protected <T> T doGetBean(final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
1.去掉&开头
final String beanName = transformedBeanName(name);
else {
//可能是一个循环引用,因为拿不到bean但是却处于创建状态
if (isPrototypeCurrentlyInCreation(beanName)) {
//Requested bean is currently in creation: Is there an unresolvable circular reference?
throw new BeanCurrentlyInCreationException(beanName);
}
4.在父BeanFactory查找
BeanFactory parentBeanFactory = getParentBeanFactory();
//本beanfactory找不到
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// 找不到拿原始名去找
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
5.创建标记,(用于清除)
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
6.寻找bean定义信息,并针对bean定义进行验证
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
7.处理依赖信息,这里会针对xml定义中的depends-on进行处理
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dependsOnBean : dependsOn) {
if (isDependent(beanName, dependsOnBean)) {
....
registerDependentBean(dependsOnBean, beanName);
getBean(dependsOnBean);
}
}
初始化示例
我们先来看下spring如何手动初始化一个对象
spring源码解析
所以我们先从DefaultListableBeanFactory开始了解
AbstractBeanFactory
具体通过这个私有方法来解决依赖的 假设A依赖于B,那么在创建A之前,必须保证B先被创建。 在创建了B之后,这里会进行依赖信息存储。后面在递归调用一下,不过依赖关系反过来。 dependentBeanMap放 A->[B,C,D] (A所依赖的B,C,D)
单例模式就调用getSingleton(String beanName, ObjectFactory<?> singletonFactory)
原型模式,来一次创一个
其他模式,比如scope=request
10.Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)
Spring生命周期
通过源码我们清晰的看到
如果已经能拿到相应的bean则直接返回不进行下面的操作
本bean如果
实现了BeanNameAware就调用setBeanName把bean名字放入
实现了BeanClassLoaderAware就调用setBeanClassLoader把ClassLoader放入
实现了BeanFactoryAware调用setBeanFactory把BeanFactory放入
刚才反复提到了几个接口,我们来单独看下他们的使用:
InstantiationAwareBeanPostProcessor接口
BeanNameAware接口,通过实现这个接口可以获取到bean的id名
BeanClassLoaderAware接口,可以获取到bean的ClassLoader
BeanFactoryAware接口,通过实现这个接口可以获取到beanFactory
ApplicationContextAware接口,获取ApplicationContext
BeanPostProcessor接口
InitializingBean接口
DisposableBean接口