微信公眾號:bugstack蟲洞棧 | 博客:https:// 沉淀、分享、成長,專注于原創(chuàng)專題案例,以最易學習編程的方式分享知識,讓自己和他人都能有所收獲。目前已完成的專題有;Netty4.x實戰(zhàn)專題案例、用Java實現JVM、基于JavaAgent的全鏈路監(jiān)控、手寫RPC框架、架構設計專題案例[Ing]等。 你用劍🗡、我用刀🔪,好的代碼都很燒😏,望你不吝出招💨!
一、前言介紹
往往簡單的背后都有人為你承擔著不簡單,Spring 就是這樣的家伙!而分析它的源碼就像鬼吹燈,需要尋龍、點穴、分金、定位,最后往往受點傷(時間)、流點血(精力)、才能獲得寶藏(成果)。
另外鑒于之前分析spring-mybatis、quartz,一篇寫了將近2萬字,內容過于又長又干,挖藏師好辛苦,看戲的也憋著腎,所以這次分析spring源碼分塊解讀,便于理解、便于消化。
那么,這一篇就從 bean 的加載開始,從 xml 配置文件解析 bean 的定義,到注冊到 Spring 的核心類 DefaultListableBeanFactory ,盜墓過程如下;
從上圖可以看到從 xml 解析出 bean 到注冊完成需要經歷過8個核心類以及22個方法跳轉流程,這也是本文后面需要重點分析的內容。好!那么就當為了你的錢程 一起盜墓吧!
二、案例工程
對于源碼分析一定要單獨列一個簡單的工程,一針見血的搞你最需要的地方,模擬、驗證、調試?,F在這個案例工程還很簡單,隨著后面分析內容的增加,會不斷的擴充。整體工程可以下載,可以關注公眾號: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
三、環(huán)境配置
JDK 1.8 IDEA 2019.3.1 Spring 4.3.24.RELEASE
四、源碼分析
整個 bean 注冊過程核心功能包括;配置文件加載、工廠創(chuàng)建、XML解析、Bean定義、Bean注冊,執(zhí)行流程如下;
從上圖的注冊 bean 流程看到,核心類包括;
ClassPathXmlApplicationContext AbstractXmlApplicationContext AbstractRefreshableApplicationContext AbstractXmlApplicationContext AbstractBeanDefinitionReader XmlBeanDefinitionReader DefaultBeanDefinitionDocumentReader DefaultListableBeanFactory
好!摸金分金定穴完事,搬山的搬山、卸嶺的卸嶺,開始搞!
1. 先扔個 helloworld 測試下
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./schema/beans"
xmlns: xsi= "http://www./2001/XMLSchema-instance"
xsi: schemaLocation= "http://www./schema/beans http://www./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 ( 1000 L) ) ;
}
@Test
public void test_ClassPathXmlApplicationContext ( ) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext ( "spring-config.xml" ) ;
UserService userService = beanFactory. getBean ( "userService" , UserService. class ) ;
logger. info ( "測試結果:{}" , userService. queryUserInfo ( 1000 L) ) ;
}
兩個單測方法都可以做結果輸出,但是 XmlBeanFactory 已經標記為 @Deprecated 就是告訴我們這個墓穴啥也沒有了,被盜過了,別看了。好!我們也不看他了,我們看現在推薦的2號墓 ClassPathXmlApplicationContext
如上不出意外正確結果如下;
23 : 34 : 24.699 [ main] INFO org. itstack. demo. test. ApiTest - 測試結果:花花 id:1000
Process finished with exit code 0
2. 把 xml 解析過程搞定
在整個 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 創(chuàng)建時候需要的參數信息進行組裝,如下;
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 節(jié)點信息,最后輸出節(jié)點內容,如下;
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 進行處理了。紅姑娘、鷓鴣哨、咱們出發(fā)!
3. ClassPathXmlApplicationContext 構造函數初始化過程
ClassPathXmlApplicationContext.java & 截取部分代碼
public ClassPathXmlApplicationContext ( String[ ] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super ( parent) ;
setConfigLocations ( configLocations) ;
if ( refresh) {
refresh ( ) ;
}
}
源碼139行: setConfigLocations 設置我們的配置的資源位置信息重點在 refresh() 這個方法里面內容非常多,隨著文章的編寫會陸續(xù)分析。
4. AbstractApplicationContext 初始化工廠
AbstractApplicationContext.java & 部分代碼截取
@Override
public void refresh ( ) throws BeansException, IllegalStateException {
synchronized ( this . startupShutdownMonitor) {
// 設置容器初始化
prepareRefresh ( ) ;
// 讓子類進行 BeanFactory 初始化,并且將 Bean 信息 轉換為 BeanFinition,最后注冊到容器中
// 注意,此時 Bean 還沒有初始化,只是配置信息都提取出來了
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory ( ) ;
. . .
}
}
源碼514行: 這一行是我們重點往后分析的內容,它主要開始處理 xml 中 bean 的初始化過程,但此時不會注冊,意思就是你通過 beanFactory.getBean 還獲得不到內容
AbstractApplicationContext.java & 部分代碼截取
protected ConfigurableListableBeanFactory obtainFreshBeanFactory ( ) {
refreshBeanFactory ( ) ;
ConfigurableListableBeanFactory beanFactory = getBeanFactory ( ) ;
if ( logger. isDebugEnabled ( ) ) {
logger. debug ( "Bean factory for " + getDisplayName ( ) + ": " + beanFactory) ;
}
return beanFactory;
}
這一層方法在處理完解析后還會返回 bean 工廠 源碼614行: 回到我們主線繼續(xù)分析解析過程,往下一層繼續(xù)看
5. AbstractRefreshableApplicationContext 刷新上下文
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) ;
}
}
這里包括判斷對 bean 工廠判斷的以及銷毀和初始化創(chuàng)建 源碼129行: loadBeanDefinitions(beanFactory);,獲取 bean 工廠后繼續(xù)我們 bean 注冊過程
6. AbstractXmlApplicationContext xml配置處理
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) ;
}
源碼82行: XmlBeanDefinitionReader 定義配置文件讀取類,并設置基礎的屬性信息,getEnvironment、ResourceEntityResolver源碼93行: loadBeanDefinitions 在拿到 beanDefinitionReader 繼續(xù)執(zhí)行
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) ;
}
}
源碼121行: 獲取我們最開始設置的資源信息,在這里也就是 spring-config.xml源碼127行: 通過 beanDefinitionReader 開始加載解析配置文件
7. AbstractBeanDefinitionReader 配置文件加載
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;
}
抽象類是中提供了加載解析的方法,每解析一組就計數一次 源碼252行: loadBeanDefinitions(location) 循環(huán)加載 bean 的定義進行解析
AbstractBeanDefinitionReader.java & 部分代碼截取
public int loadBeanDefinitions ( String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions ( location, null) ;
}
類內部提供的單個解析方法,沒有什么特別。繼續(xù)往下
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;
}
}
源碼217行: 獲取資源解析,最終執(zhí)行到 loadBeanDefinitions(resources);,繼續(xù)往下
8. XmlBeanDefinitionReader 配置解析
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 ( ) ;
}
}
}
源碼330行 -> 336行: 這個就是 xml 的解析過程,在我們最開始優(yōu)先分析的部分,這一部分真正的要為解析 xml 做準備
9. XmlBeanDefinitionReader 配置文件讀取
XmlBeanDefinitionReader.java & 部分代碼截取
protected int doLoadBeanDefinitions ( InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
Document doc = doLoadDocument ( inputSource, resource) ;
return registerBeanDefinitions ( doc, resource) ;
} catch ( ) { }
}
源碼391行: 此時就獲取到了 Document ,這里面就包括了所有的節(jié)點信息,也就是我們的 bean 的定義源碼392行: 通過 doc 與 資源信息開始定義 bean 等待注冊,這個注冊 bean 的過程是需要先定義 bean 的內容,每一個 bean 都需要用 BeanDefinitionHolder 封裝
10. DefaultBeanDefinitionDocumentReader 定義bean類
DefaultBeanDefinitionDocumentReader.java & 部分代碼截取
public void registerBeanDefinitions ( Document doc, XmlReaderContext readerContext) {
this . readerContext = readerContext;
logger. debug ( "Loading bean definitions" ) ;
Element root = doc. getDocumentElement ( ) ;
doRegisterBeanDefinitions ( root) ;
}
源碼93行: 越來越熟悉了吧,開始獲取節(jié)點元素了,也就可以獲取 bean 信息
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) ;
}
}
NodeList 循環(huán)處理節(jié)點內容,開啟注冊 源碼169行: parseDefaultElement(ele, delegate); 解析元素操作
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) ;
}
}
這個方法會根據不同的節(jié)點類型;IMPORT_ELEMENT、ALIAS_ELEMENT、BEAN_ELEMENT、NESTED_BEANS_ELEMENT,進行不同的操作 源碼190行: 這里我們只需要關注 processBeanDefinition(ele, delegate) 即可,處理 bean 操作
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) ) ;
}
}
如果你認真的讀文章了,BeanDefinitionHolder 我們在上面已經說過一次,這是每一個 bean 都會定義的操作,最后交給注冊中心 源碼304行: BeanDefinitionReaderUtils.registerBeanDefinition,類里的一個靜態(tài)注冊操作方法
11. BeanDefinitionReaderUtils bean注冊工具類
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) ;
}
}
}
源碼149行: 將 beanName、BeanDefinition,一同交給最后的注冊中心,最后這個就是 DefaultListableBeanFactory
12. DefaultListableBeanFactory bean核心注冊中心
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) ;
}
}
五、綜上總結
陳玉樓的盜墓(源碼分析),初步確定了路線、墓室、干掉了蜈蚣,今天大家勝利而歸,開始收拾整理裝備 源碼分析真的就像盜墓一樣,分析前一切都是陌生的,一遍遍的分析后會從里面不斷的獲取寶藏,這個寶藏的多少取決你對他的挖掘深度 本次只是簡單的分析了一個 xml 中配置的 bean 注冊的過程,此時還沒有真正的生成 bean,等下篇文章繼續(xù)分析
六、關注公眾號