微信公眾號:bugstack蟲洞棧 | 博客:https://bugstack.cn
沉淀、分享、成長,專注于原創(chuàng)專題案例,以最易學(xué)習(xí)編程的方式分享知識,讓自己和他人都能有所收獲。目前已完成的專題有;Netty4.x實(shí)戰(zhàn)專題案例、用Java實(shí)現(xiàn)JVM、基于JavaAgent的全鏈路監(jiān)控、手寫RPC框架、架構(gòu)設(shè)計(jì)專題案例[Ing]等。
你用劍🗡、我用刀🔪,好的代碼都很燒😏,望你不吝出招💨!
往往簡單的背后都有人為你承擔(dān)著不簡單,Spring 就是這樣的家伙!而分析它的源碼就像鬼吹燈,需要尋龍、點(diǎn)穴、分金、定位,最后往往受點(diǎn)傷(時(shí)間)、流點(diǎn)血(精力)、才能獲得寶藏(成果)。
另外鑒于之前分析spring-mybatis、quartz,一篇寫了將近2萬字,內(nèi)容過于又長又干,挖藏師好辛苦,看戲的也憋著腎,所以這次分析spring源碼分塊解讀,便于理解、便于消化。
那么,這一篇就從 bean 的加載開始,從 xml 配置文件解析 bean 的定義,到注冊到 Spring 的核心類 DefaultListableBeanFactory ,盜墓過程如下;
從上圖可以看到從 xml 解析出 bean 到注冊完成需要經(jīng)歷過8個(gè)核心類以及22個(gè)方法跳轉(zhuǎn)流程,這也是本文后面需要重點(diǎn)分析的內(nèi)容。好!那么就當(dāng)為了你的錢程一起盜墓吧!
對于源碼分析一定要單獨(dú)列一個(gè)簡單的工程,一針見血的搞你最需要的地方,模擬、驗(yàn)證、調(diào)試?,F(xiàn)在這個(gè)案例工程還很簡單,隨著后面分析內(nèi)容的增加,會不斷的擴(kuò)充。整體工程可以下載,可以關(guān)注公眾號:bugstack蟲洞棧 | 回復(fù):源碼分析
itstack-demo-code-spring
└── src
├── main
│ ├── java
│ │ └── org.itstack.demo
│ │ └── UserService.java
│ └── resources
│ └── spring-config.xml
└── test
└── java
└── org.itstack.demo.test
└── ApiTest.java
整個(gè) bean 注冊過程核心功能包括;配置文件加載、工廠創(chuàng)建、XML解析、Bean定義、Bean注冊,執(zhí)行流程如下;
從上圖的注冊 bean 流程看到,核心類包括;
好!摸金分金定穴完事,搬山的搬山、卸嶺的卸嶺,開始搞!
UserService.java & 定義一個(gè) bean,Spring 萬物皆可 bean
public class UserService {
public String queryUserInfo(Long userId) {
return "花花 id:" + userId;
}
}
spring-config.xml & 在 xml 配置 bean 內(nèi)容
<?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("測試結(jié)果:{}", userService.queryUserInfo(1000L));
}
@Test
public void test_ClassPathXmlApplicationContext() {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-config.xml");
UserService userService = beanFactory.getBean("userService", UserService.class);
logger.info("測試結(jié)果:{}", userService.queryUserInfo(1000L));
}
兩個(gè)單測方法都可以做結(jié)果輸出,但是 XmlBeanFactory 已經(jīng)標(biāo)記為 @Deprecated 就是告訴我們這個(gè)墓穴啥也沒有了,被盜過了,別看了。好!我們也不看他了,我們看現(xiàn)在推薦的2號墓 ClassPathXmlApplicationContext
如上不出意外正確結(jié)果如下;
23:34:24.699 [main] INFO org.itstack.demo.test.ApiTest - 測試結(jié)果:花花 id:1000
Process finished with exit code 0
在整個(gè) bean 的注冊過程中,xml 解析是非常大的一塊,也是非常重要的一塊。如果順著 bean 工廠初始化分析,那么一層層扒開,就像陳玉樓墓穴挖到一半,遇到大蜈蚣一樣難纏。所以我們先把蜈蚣搞定!
@Test
public void test_DocumentLoader() throws Exception {
// 設(shè)置資源
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);
// 輸出結(jié)果
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("測試結(jié)果 beanName:{} beanClass:{} scope:{}", id, clazz, scope);
}
}
可能初次看這段代碼還是有點(diǎn)暈的,但這樣提煉出來單獨(dú)解決,至少給你一種有抓手的感覺。在 spring 解析 xml 時(shí)候首先是將配置資源交給 ClassPathResource ,再通過構(gòu)造函數(shù)傳遞給 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;
}
以上這個(gè)過程還是比較簡單的,只是一個(gè)初始化過程。接下來是通過 Document 解析處理 xml 文件。這個(gè)過程是仿照 spring 創(chuàng)建時(shí)候需要的參數(shù)信息進(jìn)行組裝,如下;
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 里面此時(shí)包含了所有 xml 的各個(gè) Node 節(jié)點(diǎn)信息,最后輸出節(jié)點(diǎn)內(nèi)容,如下;
Element root = doc.getDocumentElement();
NodeList nodeList = root.getChildNodes();
好!測試一下,正常情況下,結(jié)果如下;
23:47:00.249 [main] INFO org.itstack.demo.test.ApiTest - 測試結(jié)果 beanName:userService beanClass:org.itstack.demo.UserService scope:singleton
Process finished with exit code 0
可以看到的我們的 xml 配置內(nèi)容已經(jīng)完完整整的取出來了,接下來就交給 spring 進(jìn)行處理了。紅姑娘、鷓鴣哨、咱們出發(fā)!
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) {
// 設(shè)置容器初始化
prepareRefresh();
// 讓子類進(jìn)行 BeanFactory 初始化,并且將 Bean 信息 轉(zhuǎn)換為 BeanFinition,最后注冊到容器中
// 注意,此時(shí) 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 {
// 判斷驗(yàn)證
...
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);
}
}
源碼853行: 這就是最終我們將 xml 中的配置信息注冊到了配置中心,beanDefinitionMap,同時(shí)還會寫入到 beanDefinitionNames
看下最終的注入結(jié)果,嗯!我們的盜墓挖到了一點(diǎn)寶物;