轉(zhuǎn)帖|行業(yè)資訊|編輯:郝浩|2016-02-24 09:54:46.000|閱讀 909 次
概述:本篇講解了如何創(chuàng)建Bean實(shí)例并構(gòu)建Bean的關(guān)系網(wǎng)
# 界面/圖表報(bào)表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關(guān)鏈接:
下面是Bean的實(shí)例化代碼,是從finishBeanFactoryInitialization方法開始的。
protected void finishBeanFactoryInitialization( ConfigurableListableBeanFactory beanFactory) { // Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes . beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. beanFactory.preInstantiateSingletons(); }
從上面代碼中可以發(fā)現(xiàn)Bean的實(shí)例化是在BeanFactory中發(fā)生的。preInstantiateSingletons方法的代碼如下:
public void preInstantiateSingletons() throws BeansException { if (this.logger.isInfoEnabled()) { this.logger.info("Pre- instantiating singletons in " + this); } synchronized (this.beanDefinitionMap) { for (String beanName : this.beanDefinitionNames) { RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { final FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX+ beanName); boolean isEagerInit; if (System.getSecurityManager() != null && ;factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged( &nb sp; new PrivilegedAction<Boolean>() { &nb sp; public Boolean run() { return ((SmartFactoryBean) factory).isEagerInit(); &nb sp; } }, getAcce ssControlContext()); } else { isEagerInit = factory instanceof SmartFactoryBean &nb sp; && ((SmartFactoryBean) factory).isEagerInit(); } if (isEagerInit) { getBean (beanName); } } else { getBean(beanName); } } } } }
這里出現(xiàn)了一個非常重要的Bean——FactoryBean,可以說Spring一大半的擴(kuò)展的功能都與這個Bean有關(guān),這是個特殊的Bean他是個工廠Bean,可以產(chǎn)生Bean的Bean,這里的產(chǎn)生Bean是指 Bean的實(shí)例,如果一個類繼承FactoryBean用戶可以自己定義產(chǎn)生實(shí)例對象的方法只要實(shí)現(xiàn)他的getObject方法。然而在Spring內(nèi)部這個Bean的實(shí)例對象是FactoryBean,通過調(diào)用這個對象的getObject方 法就能獲取用戶自定義產(chǎn)生的對象,從而為Spring提供了很好的擴(kuò)展性。Spring獲取FactoryBean本身的對象是在前面加上&來完成的。
如何創(chuàng)建Bean的實(shí)例對象以及如何構(gòu)建Bean實(shí)例對象之間的關(guān)聯(lián)關(guān)系式Spring中的一個核心關(guān)鍵,下面是這個過程的流程圖。
如果是普通的Bean就直接創(chuàng)建他的實(shí)例,是通過調(diào)用getBean方法。下面是創(chuàng)建Bean實(shí)例的時序圖:
還有一個非常重要的部分就是建立Bean對象實(shí)例之間的關(guān)系,這也是Spring框架的核心競爭力,何時、如何建立他們之間的關(guān)系請看下面的時序圖:
本站文章除注明轉(zhuǎn)載外,均為本站原創(chuàng)或翻譯。歡迎任何形式的轉(zhuǎn)載,但請務(wù)必注明出處、不得修改原文相關(guān)鏈接,如果存在內(nèi)容上的異議請郵件反饋至chenjj@fc6vip.cn