微信公衆號:bugstack蟲洞棧 | 博客: https://bugstack.cn
<br/>沉澱、分享、成長,專一於原創專題案例,以最易學習編程的方式分享知識,讓本身和他人都能有所收穫。目前已完成的專題有;Netty4.x實戰專題案例、用Java實現JVM、基於JavaAgent的全鏈路監控、手寫RPC框架、架構設計專題案例[Ing]等。
<br/>你用劍🗡、我用刀🔪,好的代碼都很燒😏,望你不吝出招💨!
每每簡單的背後都有人爲你承擔着不簡單,Spring 就是這樣的傢伙!而分析它的源碼就像鬼吹燈,須要尋龍、點穴、分金、定位,最後每每受點傷(時間)、流點血(精力)、才能得到寶藏(成果)。java
另外鑑於以前分析spring-mybatis、quartz,一篇寫了將近2萬字,內容過於又長又幹,挖藏師好辛苦,看戲的也憋着腎,因此此次分析spring源碼分塊解讀,便於理解、便於消化。node
那麼,這一篇就從 bean 的加載開始,從 xml 配置文件解析 bean 的定義,到註冊到 Spring 的核心類 DefaultListableBeanFactory ,盜墓過程以下;spring
從上圖能夠看到從 xml 解析出 bean 到註冊完成須要經歷過8個核心類以及22個方法跳轉流程,這也是本文後面須要重點分析的內容。好!那麼就當爲了你的錢程一塊兒盜墓吧!編程
對於源碼分析必定要單獨列一個簡單的工程,一針見血的搞你最須要的地方,模擬、驗證、調試。如今這個案例工程還很簡單,隨着後面分析內容的增長,會不斷的擴充。總體工程能夠下載,能夠關注公衆號:bugstack蟲洞棧 | 回覆:源碼分析微信
itstack-demo-code-spring └── src ├── main │ ├── java │ │ └── org.itstack.demo │ │ └── UserService.java │ └── resources │ └── spring-config.xml └── test └── java └── org.itstack.demo.test └── ApiTest.java
整個 bean 註冊過程核心功能包括;配置文件加載、工廠建立、XML解析、Bean定義、Bean註冊,執行流程以下;mybatis
從上圖的註冊 bean 流程看到,核心類包括;架構
好!摸金分金定穴完事,搬山的搬山、卸嶺的卸嶺,開始搞!框架
UserService.java & 定義一個 bean,Spring 萬物皆可 bean
public class UserService { public String queryUserInfo(Long userId) { return "花花 id:" + userId; } }
spring-config.xml & 在 xml 配置 bean 內容
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" default-autowire="byName"> <bean id="userService" class="org.itstack.demo.UserService" scope="singleton"/> </beans>
ApiTest.java & 單元測試類
@Test public void test_XmlBeanFactory() { BeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("spring-config.xml")); UserService userService = beanFactory.getBean("userService", UserService.class); logger.info("測試結果:{}", userService.queryUserInfo(1000L)); } @Test public void test_ClassPathXmlApplicationContext() { BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml"); UserService userService = beanFactory.getBean("userService", UserService.class); logger.info("測試結果:{}", userService.queryUserInfo(1000L)); }
兩個單測方法均可以作結果輸出,可是 XmlBeanFactory 已經標記爲 @Deprecated 就是告訴咱們這個墓穴啥也沒有了,被盜過了,別看了。好!咱們也不看他了,咱們看如今推薦的2號墓 ClassPathXmlApplicationContextdom
如上不出意外正確結果以下;ide
23:34:24.699 [main] INFO org.itstack.demo.test.ApiTest - 測試結果:花花 id:1000 Process finished with exit code 0
在整個 bean 的註冊過程當中,xml 解析是很是大的一塊,也是很是重要的一塊。若是順着 bean 工廠初始化分析,那麼一層層扒開,就像陳玉樓墓穴挖到一半,遇到大蜈蚣同樣難纏。因此咱們先把蜈蚣搞定!
@Test public void test_DocumentLoader() throws Exception { // 設置資源 EncodedResource encodedResource = new EncodedResource(new ClassPathResource("spring-config.xml")); // 加載解析 InputSource inputSource = new InputSource(encodedResource.getResource().getInputStream()); DocumentLoader documentLoader = new DefaultDocumentLoader(); Document doc = documentLoader.loadDocument(inputSource, new ResourceEntityResolver(new PathMatchingResourcePatternResolver()), new DefaultHandler(), 3, false); // 輸出結果 Element root = doc.getDocumentElement(); NodeList nodeList = root.getChildNodes(); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (!(node instanceof Element)) continue; Element ele = (Element) node; if (!"bean".equals(ele.getNodeName())) continue; String id = ele.getAttribute("id"); String clazz = ele.getAttribute("class"); String scope = ele.getAttribute("scope"); logger.info("測試結果 beanName:{} beanClass:{} scope:{}", id, clazz, scope); } }
可能初次看這段代碼仍是有點暈的,但這樣提煉出來單獨解決,至少給你一種有抓手的感受。在 spring 解析 xml 時候首先是將配置資源交給 ClassPathResource ,再經過構造函數傳遞給 EncodedResource;
private EncodedResource(Resource resource, String encoding, Charset charset) { super(); Assert.notNull(resource, "Resource must not be null"); this.resource = resource; this.encoding = encoding; this.charset = charset; }
以上這個過程仍是比較簡單的,只是一個初始化過程。接下來是經過 Document 解析處理 xml 文件。這個過程是仿照 spring 建立時候須要的參數信息進行組裝,以下;
documentLoader.loadDocument(inputSource, new ResourceEntityResolver(new PathMatchingResourcePatternResolver()), new DefaultHandler(), 3, false); public Document loadDocument(InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception { DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware); if (logger.isDebugEnabled()) { logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]"); } DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler); return builder.parse(inputSource); }
經過上面的代碼獲取 org.w3c.dom.Document, Document 裏面此時包含了全部 xml 的各個 Node 節點信息,最後輸出節點內容,以下;
Element root = doc.getDocumentElement(); NodeList nodeList = root.getChildNodes();
好!測試一下,正常狀況下,結果以下;
23:47:00.249 [main] INFO org.itstack.demo.test.ApiTest - 測試結果 beanName:userService beanClass:org.itstack.demo.UserService scope:singleton Process finished with exit code 0
能夠看到的咱們的 xml 配置內容已經完完整整的取出來了,接下來就交給 spring 進行處理了。紅姑娘、鷓鴣哨、我們出發!
ClassPathXmlApplicationContext.java & 截取部分代碼
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException { super(parent); setConfigLocations(configLocations); if (refresh) { refresh(); } }
AbstractApplicationContext.java & 部分代碼截取
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 設置容器初始化 prepareRefresh(); // 讓子類進行 BeanFactory 初始化,而且將 Bean 信息 轉換爲 BeanFinition,最後註冊到容器中 // 注意,此時 Bean 尚未初始化,只是配置信息都提取出來了 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); ... } }
AbstractApplicationContext.java & 部分代碼截取
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (logger.isDebugEnabled()) { logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory); } return beanFactory; }
AbstractRefreshableApplicationContext.java & 部分代碼截取
protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
AbstractXmlApplicationContext.java & 部分代碼截取
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { // Create a new XmlBeanDefinitionReader for the given BeanFactory. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's // resource loading environment. beanDefinitionReader.setEnvironment(this.getEnvironment()); beanDefinitionReader.setResourceLoader(this); beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader, // then proceed with actually loading the bean definitions. initBeanDefinitionReader(beanDefinitionReader); loadBeanDefinitions(beanDefinitionReader); }
AbstractXmlApplicationContext.java & 部分代碼截取
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { Resource[] configResources = getConfigResources(); if (configResources != null) { reader.loadBeanDefinitions(configResources); } String[] configLocations = getConfigLocations(); if (configLocations != null) { reader.loadBeanDefinitions(configLocations); } }
AbstractBeanDefinitionReader.java & 部分代碼截取
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException { Assert.notNull(locations, "Location array must not be null"); int counter = 0; for (String location : locations) { counter += loadBeanDefinitions(location); } return counter; }
AbstractBeanDefinitionReader.java & 部分代碼截取
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException { return loadBeanDefinitions(location, null); }
AbstractBeanDefinitionReader.java & 部分代碼截取
public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException { ResourceLoader resourceLoader = getResourceLoader(); if (resourceLoader == null) { throw new BeanDefinitionStoreException( "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available"); } if (resourceLoader instanceof ResourcePatternResolver) { // Resource pattern matching available. try { Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location); int loadCount = loadBeanDefinitions(resources); if (actualResources != null) { for (Resource resource : resources) { actualResources.add(resource); } } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]"); } return loadCount; } catch (IOException ex) { throw new BeanDefinitionStoreException( "Could not resolve bean definition resource pattern [" + location + "]", ex); } } else { // Can only load single resources by absolute URL. Resource resource = resourceLoader.getResource(location); int loadCount = loadBeanDefinitions(resource); if (actualResources != null) { actualResources.add(resource); } if (logger.isDebugEnabled()) { logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]"); } return loadCount; } }
XmlBeanDefinitionReader.java & 部分代碼截取
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { // 判斷驗證 ... try { InputStream inputStream = encodedResource.getResource().getInputStream(); try { InputSource inputSource = new InputSource(inputStream); if (encodedResource.getEncoding() != null) { inputSource.setEncoding(encodedResource.getEncoding()); } return doLoadBeanDefinitions(inputSource, encodedResource.getResource()); } finally { inputStream.close(); } } catch (IOException ex) { throw new BeanDefinitionStoreException( "IOException parsing XML document from " + encodedResource.getResource(), ex); } finally { currentResources.remove(encodedResource); if (currentResources.isEmpty()) { this.resourcesCurrentlyBeingLoaded.remove(); } } }
XmlBeanDefinitionReader.java & 部分代碼截取
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException { try { Document doc = doLoadDocument(inputSource, resource); return registerBeanDefinitions(doc, resource); } catch(){} }
DefaultBeanDefinitionDocumentReader.java & 部分代碼截取
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) { this.readerContext = readerContext; logger.debug("Loading bean definitions"); Element root = doc.getDocumentElement(); doRegisterBeanDefinitions(root); }
DefaultBeanDefinitionDocumentReader.java & 部分代碼截取
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate deleg if (delegate.isDefaultNamespace(root)) { NodeList nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { Node node = nl.item(i); if (node instanceof Element) { Element ele = (Element) node; if (delegate.isDefaultNamespace(ele)) { parseDefaultElement(ele, delegate); } else { delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } }
DefaultBeanDefinitionDocumentReader.java & 部分代碼截取
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { importBeanDefinitionResource(ele); } else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { processAliasRegistration(ele); } else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { processBeanDefinition(ele, delegate); } else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { // recurse doRegisterBeanDefinitions(ele); } }
DefaultBeanDefinitionDocumentReader.java & 部分代碼截取
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele); if (bdHolder != null) { bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder); try { // Register the final decorated instance. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); } catch (BeanDefinitionStoreException ex) { getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, ex); } // Send registration event. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder)); } }
BeanDefinitionReaderUtils.java & 部分代碼截取
public static void registerBeanDefinition( BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry) throws BeanDefinitionStoreException { // Register bean definition under primary name. String beanName = definitionHolder.getBeanName(); registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // Register aliases for bean name, if any. String[] aliases = definitionHolder.getAliases(); if (aliases != null) { for (String alias : aliases) { registry.registerAlias(beanName, alias); } } }
DefaultListableBeanFactory.java & 部分代碼截取
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { Assert.hasText(beanName, "Bean name must not be empty"); Assert.notNull(beanDefinition, "BeanDefinition must not be null"); if (beanDefinition instanceof AbstractBeanDefinition) { try { ((AbstractBeanDefinition) beanDefinition).validate(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName, "Validation of bean definition failed", ex); } } BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName); if (existingDefinition != null) { ... } else { ... else { // Still in startup registration phase this.beanDefinitionMap.put(beanName, beanDefinition); this.beanDefinitionNames.add(beanName); this.manualSingletonNames.remove(beanName); } this.frozenBeanDefinitionNames = null; } if (existingDefinition != null || containsSingleton(beanName)) { resetBeanDefinition(beanName); } }