源碼app
AbstractApplicationContext#public void refresh() throws BeansException, IllegalStateException { finishBeanFactoryInitialization(beanFactory); }; protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { beanFactory.preInstantiateSingletons(); } DefaultListableBeanFactory#public void preInstantiateSingletons() throws BeansException { getBean(beanName); } AbstractBeanFactory#public Object getBean(String name) throws BeansException { return doGetBean(name, null, null, false); } protected <T> T doGetBean() { return createBean(beanName, mbd, args); } AbstractAutowireCapableBeanFactory#protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException { Object beanInstance = doCreateBean(beanName, mbdToUse, args); } protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { exposedObject = initializeBean(beanName, exposedObject, mbd); } protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) { // 第二個參數bean,此時已經實例化好了,也已經屬性注入了 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName); } public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) { result = beanProcessor.postProcessAfterInitialization(result, beanName); } interface BeanPostProcessor#Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException; AbstractAutoProxyCreator#public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (bean != null) { Object cacheKey = getCacheKey(bean.getClass(), beanName); // 判斷是否須要對此Bean生成代理 if (!this.earlyProxyReferences.contains(cacheKey)) { return wrapIfNecessary(bean, beanName, cacheKey); } } return bean; } protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) { if (beanName != null && this.targetSourcedBeans.contains(beanName)) { return bean; } if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { return bean; } if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) { this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; } // Create proxy if we have advice. Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null); if (specificInterceptors != DO_NOT_PROXY) { this.advisedBeans.put(cacheKey, Boolean.TRUE); // 生成代理類 Object proxy = createProxy( bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean)); this.proxyTypes.put(cacheKey, proxy.getClass()); return proxy; } this.advisedBeans.put(cacheKey, Boolean.FALSE); return bean; }