获取xml文件路径,使用IO读取xml文件,使用Document对象解析xml文件,将xml中的bean的信息注册到BeanDefinition类,将BeanDefinition保存到一个map中;该类作用是将javabean的信息转化为spring数据结构;随后调用spring的类加载器,将类加载到内存中,接着对类进行初始化(这个初始化只是将的成员变量赋予初始值(0),还未将它们的值设为int i = 1;等调用getBean()方法时,才正式将类真正的进行初始化工作或者设置在加载类的时候就进行该初始化工作。作为一个容器,这个容器是由什么实现,HashMap?

  1. 初始化所有的 singleton beans
  2. /**
  3. * Finish the initialization of this context's bean factory,
  4. * initializing all remaining singleton beans.
  5. */
  6. protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
  7. // Initialize conversion(转换) service for this context.
  8. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
  9. beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
  10. beanFactory.setConversionService(
  11. beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
  12. }
  13.  
  14. // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
  15. //切面相关的类
  16. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
  17. for (String weaverAwareName : weaverAwareNames) {
  18. getBean(weaverAwareName);
  19. }
  20.  
  21. // Stop using the temporary ClassLoader for type matching.
  22. beanFactory.setTempClassLoader(null);
  23.  
  24. // Allow for caching all bean definition metadata, not expecting further changes.
  25. beanFactory.freezeConfiguration();
  26.  
  27. // Instantiate all remaining (non-lazy-init) singletons.
  28. //开始初始化
  29. beanFactory.preInstantiateSingletons();
  30. }
  31. ------------
  32. //DefaultListableBeanFactory类
  33. public void preInstantiateSingletons() throws BeansException {
  34. if (this.logger.isDebugEnabled()) {
  35. this.logger.debug("Pre-instantiating singletons in " + this);
  36. }
  37.  
  38. // Iterate over a copy to allow for init methods which in turn register new bean definitions.
  39. // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
  40. List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);
  41.  
  42. // Trigger initialization of all non-lazy singleton beans...
  43. for (String beanName : beanNames) {
  44. RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
  45. if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
  46. if (isFactoryBean(beanName)) {
  47. final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
  48. boolean isEagerInit;
  49. if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
  50. isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
  51. @Override
  52. public Boolean run() {
  53. return ((SmartFactoryBean<?>) factory).isEagerInit();
  54. }
  55. }, getAccessControlContext());
  56. }
  57. else {
  58. isEagerInit = (factory instanceof SmartFactoryBean &&
  59. ((SmartFactoryBean<?>) factory).isEagerInit());
  60. }
  61. if (isEagerInit) {
  62. getBean(beanName);
  63. }
  64. }
  65. else {
  66. getBean(beanName);
  67. }
  68. }
  69. }
  70.  
  71. // Trigger post-initialization callback for all applicable beans...
  72. for (String beanName : beanNames) {
  73. Object singletonInstance = getSingleton(beanName);
  74. if (singletonInstance instanceof SmartInitializingSingleton) {
  75. final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
  76. if (System.getSecurityManager() != null) {
  77. AccessController.doPrivileged(new PrivilegedAction<Object>() {
  78. @Override
  79. public Object run() {
  80. smartSingleton.afterSingletonsInstantiated();
  81. return null;
  82. }
  83. }, getAccessControlContext());
  84. }
  85. else {
  86. smartSingleton.afterSingletonsInstantiated();
  87. }
  88. }
  89. }
  90. }
  91. ----
  92. getBean()
  93. public Object getBean(String name) throws BeansException {
  94. return doGetBean(name, null, null, false);
  95. }
  96. -----
  97. protected <T> T doGetBean(
  98. final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
  99. throws BeansException {
  100.  
  101. final String beanName = transformedBeanName(name);
  102. Object bean;
  103.  
  104. // Eagerly check singleton cache for manually registered singletons.
  105. Object sharedInstance = getSingleton(beanName);
  106. if (sharedInstance != null && args == null) {
  107. if (logger.isDebugEnabled()) {
  108. if (isSingletonCurrentlyInCreation(beanName)) {
  109. logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
  110. "' that is not fully initialized yet - a consequence of a circular reference");
  111. }
  112. else {
  113. logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
  114. }
  115. }
  116. bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
  117. }
  118.  
  119. else {
  120. // Fail if we're already creating this bean instance:
  121. // We're assumably within a circular reference.
  122. if (isPrototypeCurrentlyInCreation(beanName)) {
  123. throw new BeanCurrentlyInCreationException(beanName);
  124. }
  125.  
  126. // Check if bean definition exists in this factory.
  127. BeanFactory parentBeanFactory = getParentBeanFactory();
  128. if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
  129. // Not found -> check parent.
  130. String nameToLookup = originalBeanName(name);
  131. if (args != null) {
  132. // Delegation to parent with explicit args.
  133. return (T) parentBeanFactory.getBean(nameToLookup, args);
  134. }
  135. else {
  136. // No args -> delegate to standard getBean method.
  137. return parentBeanFactory.getBean(nameToLookup, requiredType);
  138. }
  139. }
  140.  
  141. if (!typeCheckOnly) {
  142. markBeanAsCreated(beanName);
  143. }
  144.  
  145. try {
  146. final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
  147. checkMergedBeanDefinition(mbd, beanName, args);
  148.  
  149. // 处理依赖关系
  150. String[] dependsOn = mbd.getDependsOn();
  151. if (dependsOn != null) {
  152. for (String dependsOnBean : dependsOn) {
  153. if (isDependent(beanName, dependsOnBean)) {
  154. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  155. "Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
  156. }
  157. //注册依赖关系
  158. registerDependentBean(dependsOnBean, beanName);
  159. //初始化依赖对象
  160. getBean(dependsOnBean);
  161. }
  162. }
  163.  
  164. // 创建单例化实例.
  165. if (mbd.isSingleton()) {
  166. sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
  167. @Override
  168. public Object getObject() throws BeansException {
  169. try {
  170. return createBean(beanName, mbd, args);
  171. }
  172. catch (BeansException ex) {
  173. // Explicitly remove instance from singleton cache: It might have been put there
  174. // eagerly by the creation process, to allow for circular reference resolution.
  175. // Also remove any beans that received a temporary reference to the bean.
  176. destroySingleton(beanName);
  177. throw ex;
  178. }
  179. }
  180. });
  181. bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
  182. }
  183. //创建多例实例
  184. else if (mbd.isPrototype()) {
  185. // It's a prototype -> create a new instance.
  186. Object prototypeInstance = null;
  187. try {
  188. beforePrototypeCreation(beanName);
  189. prototypeInstance = createBean(beanName, mbd, args);
  190. }
  191. finally {
  192. afterPrototypeCreation(beanName);
  193. }
  194. bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
  195. }
  196.  
  197. else {
  198. String scopeName = mbd.getScope();
  199. final Scope scope = this.scopes.get(scopeName);
  200. if (scope == null) {
  201. throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
  202. }
  203. try {
  204. Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
  205. @Override
  206. public Object getObject() throws BeansException {
  207. beforePrototypeCreation(beanName);
  208. try {
  209. return createBean(beanName, mbd, args);
  210. }
  211. finally {
  212. afterPrototypeCreation(beanName);
  213. }
  214. }
  215. });
  216. bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
  217. }
  218. catch (IllegalStateException ex) {
  219. throw new BeanCreationException(beanName,
  220. "Scope '" + scopeName + "' is not active for the current thread; consider " +
  221. "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
  222. ex);
  223. }
  224. }
  225. }
  226. catch (BeansException ex) {
  227. cleanupAfterBeanCreationFailure(beanName);
  228. throw ex;
  229. }
  230. }
  231.  
  232. // Check if required type matches the type of the actual bean instance.
  233. if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
  234. try {
  235. return getTypeConverter().convertIfNecessary(bean, requiredType);
  236. }
  237. catch (TypeMismatchException ex) {
  238. if (logger.isDebugEnabled()) {
  239. logger.debug("Failed to convert bean '" + name + "' to required type [" +
  240. ClassUtils.getQualifiedName(requiredType) + "]", ex);
  241. }
  242. throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
  243. }
  244. }
  245. return (T) bean;
  246. }
  247. ------------
  248. //AbstractAutowireCapableBeanFactory 类
  249. protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
  250. if (logger.isDebugEnabled()) {
  251. logger.debug("Creating instance of bean '" + beanName + "'");
  252. }
  253. RootBeanDefinition mbdToUse = mbd;
  254.  
  255. // Make sure bean class is actually resolved at this point, and
  256. // clone the bean definition in case of a dynamically resolved Class
  257. // which cannot be stored in the shared merged bean definition.
  258. Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
  259. if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
  260. mbdToUse = new RootBeanDefinition(mbd);
  261. mbdToUse.setBeanClass(resolvedClass);
  262. }
  263.  
  264. // Prepare method overrides.
  265. try {
  266. mbdToUse.prepareMethodOverrides();
  267. }
  268. catch (BeanDefinitionValidationException ex) {
  269. throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
  270. beanName, "Validation of method overrides failed", ex);
  271. }
  272.  
  273. try {
  274. // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
  275. Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
  276. if (bean != null) {
  277. return bean;
  278. }
  279. }
  280. catch (Throwable ex) {
  281. throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
  282. "BeanPostProcessor before instantiation of bean failed", ex);
  283. }
  284. //创建bean
  285. Object beanInstance = doCreateBean(beanName, mbdToUse, args);
  286. if (logger.isDebugEnabled()) {
  287. logger.debug("Finished creating instance of bean '" + beanName + "'");
  288. }
  289. return beanInstance;
  290. }
  291. ----------
  292. protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
  293. // Instantiate the bean.
  294. BeanWrapper instanceWrapper = null;
  295. if (mbd.isSingleton()) {
  296. instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
  297. }
  298. if (instanceWrapper == null) {
  299. //创建bean实例
  300. instanceWrapper = createBeanInstance(beanName, mbd, args);
  301. }
  302. final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
  303. Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
  304.  
  305. // Allow post-processors to modify the merged bean definition.
  306. synchronized (mbd.postProcessingLock) {
  307. if (!mbd.postProcessed) {
  308. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
  309. mbd.postProcessed = true;
  310. }
  311. }
  312.  
  313. // Eagerly cache singletons to be able to resolve circular references
  314. // even when triggered by lifecycle interfaces like BeanFactoryAware.
  315. boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
  316. isSingletonCurrentlyInCreation(beanName));
  317. if (earlySingletonExposure) {
  318. if (logger.isDebugEnabled()) {
  319. logger.debug("Eagerly caching bean '" + beanName +
  320. "' to allow for resolving potential circular references");
  321. }
  322. addSingletonFactory(beanName, new ObjectFactory<Object>() {
  323. @Override
  324. public Object getObject() throws BeansException {
  325. return getEarlyBeanReference(beanName, mbd, bean);
  326. }
  327. });
  328. }
  329.  
  330. // Initialize the bean instance.
  331. Object exposedObject = bean;
  332. try {
  333. //依赖注入
  334. populateBean(beanName, mbd, instanceWrapper);
  335. if (exposedObject != null) {
  336. //处理 bean 初始化完成后的各种回调
  337. exposedObject = initializeBean(beanName, exposedObject, mbd);
  338. }
  339. }
  340. catch (Throwable ex) {
  341. if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
  342. throw (BeanCreationException) ex;
  343. }
  344. else {
  345. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
  346. }
  347. }
  348.  
  349. if (earlySingletonExposure) {
  350. Object earlySingletonReference = getSingleton(beanName, false);
  351. if (earlySingletonReference != null) {
  352. if (exposedObject == bean) {
  353. exposedObject = earlySingletonReference;
  354. }
  355. else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
  356. String[] dependentBeans = getDependentBeans(beanName);
  357. Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
  358. for (String dependentBean : dependentBeans) {
  359. if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
  360. actualDependentBeans.add(dependentBean);
  361. }
  362. }
  363. if (!actualDependentBeans.isEmpty()) {
  364. throw new BeanCurrentlyInCreationException(beanName,
  365. "Bean with name '" + beanName + "' has been injected into other beans [" +
  366. StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
  367. "] in its raw version as part of a circular reference, but has eventually been " +
  368. "wrapped. This means that said other beans do not use the final version of the " +
  369. "bean. This is often the result of over-eager type matching - consider using " +
  370. "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
  371. }
  372. }
  373. }
  374. }
  375.  
  376. // Register bean as disposable.
  377. try {
  378. registerDisposableBeanIfNecessary(beanName, bean, mbd);
  379. }
  380. catch (BeanDefinitionValidationException ex) {
  381. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
  382. }
  383.  
  384. return exposedObject;
  385. }
  386. ----------------
  387. protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
  388. // Make sure bean class is actually resolved at this point.
  389. Class<?> beanClass = resolveBeanClass(mbd, beanName);
  390.  
  391. if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
  392. throw new BeanCreationException(mbd.getResourceDescription(), beanName,
  393. "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
  394. }
  395.  
  396. if (mbd.getFactoryMethodName() != null) {
  397. return instantiateUsingFactoryMethod(beanName, mbd, args);
  398. }
  399.  
  400. // Shortcut when re-creating the same bean...
  401. boolean resolved = false;
  402. boolean autowireNecessary = false;
  403. if (args == null) {
  404. synchronized (mbd.constructorArgumentLock) {
  405. if (mbd.resolvedConstructorOrFactoryMethod != null) {
  406. resolved = true;
  407. autowireNecessary = mbd.constructorArgumentsResolved;
  408. }
  409. }
  410. }
  411. if (resolved) {
  412. if (autowireNecessary) {
  413. return autowireConstructor(beanName, mbd, null, null);
  414. }
  415. else {
  416.  
  417. return instantiateBean(beanName, mbd);
  418. }
  419. }
  420.  
  421. // Need to determine the constructor...
  422. Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
  423. if (ctors != null ||
  424. mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
  425. mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
  426. //有参构造函数的依赖注入
  427. return autowireConstructor(beanName, mbd, ctors, args);
  428. }
  429.  
  430. //无参构造函数的依赖注入
  431. return instantiateBean(beanName, mbd);
  432. }
  433. ------
  434. 无参构造函数的依赖注入
  435. protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
  436. try {
  437. Object beanInstance;
  438. final BeanFactory parent = this;
  439. if (System.getSecurityManager() != null) {
  440. beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
  441. @Override
  442. public Object run() {
  443. return getInstantiationStrategy().instantiate(mbd, beanName, parent);
  444. }
  445. }, getAccessControlContext());
  446. }
  447. else {
  448. beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
  449. }
  450. BeanWrapper bw = new BeanWrapperImpl(beanInstance);
  451. initBeanWrapper(bw);
  452. return bw;
  453. }
  454. catch (Throwable ex) {
  455. throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
  456. }
  457. }
  458. ----------
  459. public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
  460. //如果不存在方法覆写,那就使用 java 反射进行实例化,否则使用 CGLIB,
  461. if (bd.getMethodOverrides().isEmpty()) {
  462. Constructor<?> constructorToUse;
  463. synchronized (bd.constructorArgumentLock) {
  464. constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
  465. if (constructorToUse == null) {
  466. //利用反射获取类的class对象
  467. final Class<?> clazz = bd.getBeanClass();
  468. if (clazz.isInterface()) {
  469. throw new BeanInstantiationException(clazz, "Specified class is an interface");
  470. }
  471. try {
  472. if (System.getSecurityManager() != null) {
  473. constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
  474. @Override
  475. public Constructor<?> run() throws Exception {
  476. return clazz.getDeclaredConstructor((Class[]) null);
  477. }
  478. });
  479. }
  480. else {
  481. constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
  482. }
  483. bd.resolvedConstructorOrFactoryMethod = constructorToUse;
  484. }
  485. catch (Exception ex) {
  486. throw new BeanInstantiationException(clazz, "No default constructor found", ex);
  487. }
  488. }
  489. }
  490. return BeanUtils.instantiateClass(constructorToUse);
  491. }
  492. else {
  493. // 存在方法覆写,利用 CGLIB 来完成实例化,需要依赖于 CGLIB 生成子类,这里就不展开了。
  494. // tips: 因为如果不使用 CGLIB 的话,存在 override 的情况 JDK 并没有提供相应的实例化支持
  495. return instantiateWithMethodInjection(bd, beanName, owner);
  496. }
  497. }
  498. -----------
  499. bean属性的注入:
  500. protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
  501. // bean 实例的所有属性都在这里了
  502. PropertyValues pvs = mbd.getPropertyValues();
  503.  
  504. if (bw == null) {
  505. if (!pvs.isEmpty()) {
  506. throw new BeanCreationException(
  507. mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
  508. }
  509. else {
  510. // Skip property population phase for null instance.
  511. return;
  512. }
  513. }
  514.  
  515. // 到这步的时候,bean 实例化完成(通过工厂方法或构造方法),但是还没开始属性设值,
  516. // InstantiationAwareBeanPostProcessor 的实现类可以在这里对 bean 进行状态修改,
  517. boolean continueWithPropertyPopulation = true;
  518. if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
  519. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  520. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  521. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  522. // 如果返回 false,代表不需要进行后续的属性设值,也不需要再经过其他的 BeanPostProcessor 的处理
  523. if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
  524. continueWithPropertyPopulation = false;
  525. break;
  526. }
  527. }
  528. }
  529. }
  530.  
  531. if (!continueWithPropertyPopulation) {
  532. return;
  533. }
  534.  
  535. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
  536. mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
  537. MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
  538.  
  539. // 通过名字找到所有属性值,如果是 bean 依赖,先初始化依赖的 bean。记录依赖关系
  540. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
  541. autowireByName(beanName, mbd, bw, newPvs);
  542. }
  543.  
  544. // 通过类型装配。复杂一些
  545. if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
  546. autowireByType(beanName, mbd, bw, newPvs);
  547. }
  548.  
  549. pvs = newPvs;
  550. }
  551.  
  552. boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
  553. boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
  554.  
  555. if (hasInstAwareBpps || needsDepCheck) {
  556. PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
  557. if (hasInstAwareBpps) {
  558. for (BeanPostProcessor bp : getBeanPostProcessors()) {
  559. if (bp instanceof InstantiationAwareBeanPostProcessor) {
  560. InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
  561. // 这里有个非常有用的 BeanPostProcessor 进到这里: AutowiredAnnotationBeanPostProcessor
  562. // 对采用 @Autowired、@Value 注解的依赖进行设值,这里的内容也是非常丰富的,不过本文不会展开说了,感兴趣的读者请自行研究
  563. pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
  564. if (pvs == null) {
  565. return;
  566. }
  567. }
  568. }
  569. }
  570. if (needsDepCheck) {
  571. checkDependencies(beanName, mbd, filteredPds, pvs);
  572. }
  573. }
  574. // 设置 bean 实例的属性值
  575. applyPropertyValues(beanName, mbd, bw, pvs);
  576. }
  577. -----------
  578. 回调方法:
  579. protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
  580. if (System.getSecurityManager() != null) {
  581. AccessController.doPrivileged(new PrivilegedAction<Object>() {
  582. @Override
  583. public Object run() {
  584. invokeAwareMethods(beanName, bean);
  585. return null;
  586. }
  587. }, getAccessControlContext());
  588. }
  589. else {
  590. // 如果 bean 实现了 BeanNameAware、BeanClassLoaderAware 或 BeanFactoryAware 接口,回调
  591. invokeAwareMethods(beanName, bean);
  592. }
  593.  
  594. Object wrappedBean = bean;
  595. if (mbd == null || !mbd.isSynthetic()) {
  596. // BeanPostProcessor 的 postProcessBeforeInitialization 回调
  597. wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
  598. }
  599.  
  600. try {
  601. // 处理 bean 中定义的 init-method,
  602. // 或者如果 bean 实现了 InitializingBean 接口,调用 afterPropertiesSet() 方法
  603. invokeInitMethods(beanName, wrappedBean, mbd);
  604. }
  605. catch (Throwable ex) {
  606. throw new BeanCreationException(
  607. (mbd != null ? mbd.getResourceDescription() : null),
  608. beanName, "Invocation of init method failed", ex);
  609. }
  610.  
  611. if (mbd == null || !mbd.isSynthetic()) {
  612. // BeanPostProcessor 的 postProcessAfterInitialization 回调
  613. wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
  614. }
  615. return wrappedBean;
  616. }

IOC容器02的更多相关文章

  1. Spring 深入——IoC 容器 02

    IoC容器的实现学习--02 目录 IoC容器的实现学习--02 回顾 IoC 容器的初始化过程: BeanDefinition 的 Resource 定位 小结: 回顾 前面学习了 IoC 模式的核 ...

  2. Aoite 系列(02) - 超动感的 Ioc 容器

    Aoite 系列(02) - 超动感的 Ioc 容器 Aoite 是一个适于任何 .Net Framework 4.0+ 项目的快速开发整体解决方案.Aoite.Ioc 是一套解决依赖的最佳实践. 说 ...

  3. 02.Spring Ioc 容器 - 创建

    基本概念 Spring IoC 容器负责 Bean 创建.以及其生命周期的管理等.想要使用 IoC容器的前提是创建该容器. 创建 Spring IoC 容器大致有两种: 在应用程序中创建. 在 WEB ...

  4. 理解PHP 依赖注入|Laravel IoC容器

    看Laravel的IoC容器文档只是介绍实例,但是没有说原理,之前用MVC框架都没有在意这个概念,无意中在phalcon的文档中看到这个详细的介绍,感觉豁然开朗,复制粘贴过来,主要是好久没有写东西了, ...

  5. .NET自带IOC容器MEF之初体验

    .NET自带IOC容器MEF之初体验   本文主要把MEF作为一种IOC容器进行讲解,.net中可用的IOC容器非常多,如 CastleWindsor,Unity,Autofac,ObjectBuil ...

  6. Asp.Net Core 内置IOC容器的理解

    Asp.Net Core 内置IOC容器的理解 01.使用IOC容器的好处 对接口和实现类由原来的零散式管理,到现在的集中式管理. 对类和接口之间的关系,有多种注入模式(构造函数注入.属性注入等). ...

  7. Spring框架——IOC 容器的创建与使用

    企业级开发框架 Spring Framework 是整个 Spring 生态的基础,各个模块都是基于 Spring Framework 衍生出来的. Spring 的两大核心机制 IOC 控制翻转.A ...

  8. 深入理解DIP、IoC、DI以及IoC容器

    摘要 面向对象设计(OOD)有助于我们开发出高性能.易扩展以及易复用的程序.其中,OOD有一个重要的思想那就是依赖倒置原则(DIP),并由此引申出IoC.DI以及Ioc容器等概念.通过本文我们将一起学 ...

  9. IL实现简单的IOC容器

    既然了解了IL的接口和动态类之间的知识,何不使用进来项目实验一下呢?而第一反应就是想到了平时经常说的IOC容器,在园子里搜索了一下也有这类型的文章http://www.cnblogs.com/kkll ...

随机推荐

  1. 2018.09.16 loj#10241. 取石子游戏 1(博弈论)

    传送门 好像是某年的初赛题啊. 有个很显然的结论. 当n" role="presentation" style="position: relative;&quo ...

  2. 云服务器vps

    0.云计算时代,是一个很时髦的词,人们常常谈起,挂在嘴边.其实云计算通俗点就是电脑托管到了远端的机房,然后不用去买配件主机,是摸不到的,但通过网络远程连接,就可以使用云服务器的资源和功能(搭建网站,测 ...

  3. 日历时间选择控件---3(支持ie、火狐)

    效果展示:  源代码: <script language=javascript ><!--/* 调用方法:不能用onfocus,要用onclick  <input onclic ...

  4. nodejs中如何使用mysql数据库[node-mysql翻译]

    nodejs中如何使用mysql数据库 db-mysql因为node-waf: not found已经不能使用,可以使用mysql代替. 本文主要是[node-mysql]: https://www. ...

  5. shell 脚本 批量修改文件名

    修改文件名前 #!/bin/bask # for a in $( ls /etc/yum.repos.d/CentOS* );do if [ $a != '/etc/yum.repos.d/CentO ...

  6. <context:component-scan>自动扫描

    主要讲解自动扫描的<context:component-scan>中的2个子标签的使用方法 在Spring MVC中的配置中一般会遇到这两个标签,作为<context:compone ...

  7. Android-Java卖票案例-推荐此方式Runnable

    上一篇博客 Android-卖票案例static-不推荐此方式,讲解了卖票案例是 private static int ticket = 10;,static静态的这种方式来解决卖票多卖30张的问题, ...

  8. Android Studio注释摸版配置

    随意创建一个类,就会自动生成注释摸版: 配置后的效果: 以下步骤是配置过程: 1.在创建类的过程中,对类进行自定义摸版,只需在 File->Settins->Editor->File ...

  9. what is HTTP OPTIONS verb

    The options verb is sent by browser to see if server accept cross origin request or not, this proces ...

  10. C# 使用log4net写日记

    一 导入LOG4NET 打开VS2012 工具>>库程序包管理器>>管理解决方案的NuGet程序包,搜索LOG4NET,如下图 二 添加配置文件log4net.config 在 ...