本文轉(zhuǎn)自五月的倉頡 https://www.cnblogs.com/xrq730
創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比天壇街道網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式天壇街道網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋天壇街道地區(qū)。費用合理售后完善,10多年實體公司更值得信賴。
本系列文章將整理到我在GitHub上的《Java面試指南》倉庫,更多精彩內(nèi)容請到我的倉庫里查看
https://github.com/h3pl/Java-Tutorial
喜歡的話麻煩點下Star哈
文章將同步到我的個人博客:
www.how2playlife.com
本文是微信公眾號【Java技術(shù)江湖】的《Spring和SpringMVC源碼分析》其中一篇,本文部分內(nèi)容來源于網(wǎng)絡(luò),為了把本文主題講得清晰透徹,也整合了很多我認為不錯的技術(shù)博客內(nèi)容,引用其中了一些比較好的博客文章,如有侵權(quán),請聯(lián)系作者。
該系列博文會告訴你如何從spring基礎(chǔ)入手,一步步地學(xué)習(xí)spring基礎(chǔ)和springmvc的框架知識,并上手進行項目實戰(zhàn),spring框架是每一個Java工程師必須要學(xué)習(xí)和理解的知識點,進一步來說,你還需要掌握spring甚至是springmvc的源碼以及實現(xiàn)原理,才能更完整地了解整個spring技術(shù)體系,形成自己的知識框架。
后續(xù)還會有springboot和springcloud的技術(shù)專題,陸續(xù)為大家?guī)?,敬請期待?/p>
為了更好地總結(jié)和檢驗?zāi)愕膶W(xué)習(xí)成果,本系列文章也會提供部分知識點對應(yīng)的面試題以及參考答案。
如果對本系列文章有什么建議,或者是有什么疑問的話,也可以關(guān)注公眾號【Java技術(shù)江湖】聯(lián)系作者,歡迎你參與本系列博文的創(chuàng)作和修訂。
1.目標(biāo):熟練使用spring,并分析其源碼,了解其中的思想。這篇主要介紹spring ioc 容器的加載
2.前提條件:會使用debug
3.源碼分析方法:Intellj idea debug 模式下源碼追溯
通過ClassPathXmlApplicationContext 進行xml 件的讀取,從每個堆棧中讀取程序的運行信息
4.注意:由于Spring的類繼承體系比較復(fù)雜,不能全部貼圖,所以只將分析源碼之后發(fā)現(xiàn)的最主要的類繼承結(jié)構(gòu)類圖貼在下方。
5.關(guān)于Spring Ioc
Demo:我們從demo入手一步步進行代碼追溯。
1.定義數(shù)據(jù)訪問接口IUserDao.java
public interface IUserDao {
public void InsertUser(String username,String password);
}
2.定義IUserDao.java實現(xiàn)類IUserDaoImpl.java
public class UserDaoImpl implements IUserDao {
@Override
public void InsertUser(String username, String password) {
System.out.println("----UserDaoImpl --addUser----");
}
}
3.定義業(yè)務(wù)邏輯接口UserService.java
public interface UserService {
public void addUser(String username,String password);
}
4.定義UserService.java實現(xiàn)類UserServiceImpl.java
public class UserServiceImpl implements UserService {
private IUserDao userDao; //set方法
public void setUserDao(IUserDao userDao) {
this.userDao = userDao;
}
@Override
public void addUser(String username,String password) {
userDao.InsertUser(username,password);
}
}
bean.xml配置文件
<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 ">
<!--id名字自己取,class表示他代表的類,如果在包里的話需要加上包名-->
<bean id="userService" class="UserServiceImpl" >
<!--property代表是通過set方法注入,ref的值表示注入的內(nèi)容-->
<property name="userDao" ref="userDao"/>
</bean>
<bean id="userDao" class="UserDaoImpl"/>
</beans>
1.頂層接口:ApplicationContext
2.ClassPathXmlApplicationContext實現(xiàn)類繼承AbstractXmlApplication 抽象類
3.AbstractXmlApplication 繼承AbstractRefreshableConfigApplicationContext
4.AbstractRefreshableConfigApplicationContext抽象類繼承AbstractRefreshableApplicationContext
5.AbstractRefreshableApplicationContext 繼承 AbstractApplicationContext
6.AbstractApplicationContext 實現(xiàn)ConfigurableApplicationContext 接口
7.ConfigurableApplicationContext 接口繼承
ApplicationContext接口
總體來說繼承實現(xiàn)結(jié)構(gòu)較深,內(nèi)部使用了大量適配器模式。
以ClassPathXmlApplicationContext為例,繼承類圖如下圖所示:
在開始之前,先介紹一個整體的概念。即spring ioc容器的加載,大體上經(jīng)過以下幾個過程:
資源文件定位、解析、注冊、實例化
1.資源文件定位
其中資源文件定位,一般是在ApplicationContext的實現(xiàn)類里完成的,因為ApplicationContext接口繼承ResourcePatternResolver 接口,ResourcePatternResolver接口繼承ResourceLoader接口,ResourceLoader其中的getResource()方法,可以將外部的資源,讀取為Resource類。
2.解析DefaultBeanDefinitionDocumentReader,
解析主要是在BeanDefinitionReader中完成的,最常用的實現(xiàn)類是XmlBeanDefinitionReader,其中的loadBeanDefinitions()方法,負責(zé)讀取Resource,并完成后續(xù)的步驟。ApplicationContext完成資源文件定位之后,是將解析工作委托給XmlBeanDefinitionReader來完成的
解析這里涉及到很多步驟,最常見的情況,資源文件來自一個XML配置文件。首先是BeanDefinitionReader,將XML文件讀取成w3c的Document文檔。
DefaultBeanDefinitionDocumentReader對Document進行進一步解析。然后DefaultBeanDefinitionDocumentReader又委托給BeanDefinitionParserDelegate進行解析。如果是標(biāo)準(zhǔn)的xml namespace元素,會在Delegate內(nèi)部完成解析,如果是非標(biāo)準(zhǔn)的xml namespace元素,則會委托合適的NamespaceHandler進行解析最終解析的結(jié)果都封裝為BeanDefinitionHolder,至此解析就算完成。
后續(xù)會進行細致講解。
3.注冊
然后bean的注冊是在BeanFactory里完成的,BeanFactory接口最常見的一個實現(xiàn)類是DefaultListableBeanFactory,它實現(xiàn)了BeanDefinitionRegistry接口,所以其中的registerBeanDefinition()方法,可以對BeanDefinition進行注冊這里附帶一提,最常見的XmlWebApplicationContext不是自己持有BeanDefinition的,它繼承自AbstractRefreshableApplicationContext,其持有一個DefaultListableBeanFactory的字段,就是用它來保存BeanDefinition
所謂的注冊,其實就是將BeanDefinition的name和實例,保存到一個Map中。
剛才說到,最常用的實現(xiàn)DefaultListableBeanFactory,其中的字段就是beanDefinitionMap,是一個ConcurrentHashMap。
代碼如下:
>1.DefaultListableBeanFactory繼承實現(xiàn)關(guān)系
public class DefaultListableBeanFactory
extends
AbstractAutowireCapableBeanFactory
implements
ConfigurableListableBeanFactory,
BeanDefinitionRegistry,
Serializable {
// DefaultListableBeanFactory的實例中最終保存了所有注冊的bean beanDefinitionMap
/** Map of bean definition objects, keyed by bean name */
private final Map<String, BeanDefinition> beanDefinitionMap
= new ConcurrentHashMap<String, BeanDefinition>(64);
//實現(xiàn)BeanDefinitionRegistry中定義的registerBeanDefinition()抽象方法
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException {
}
>2.BeanDefinitionRegistry接口
public interface BeanDefinitionRegistry extends AliasRegistry {
//定義注冊BeanDefinition實例的抽象方法
void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException;
4.實例化
注冊也完成之后,在BeanFactory的getBean()方法之中,會完成初始化,也就是依賴注入的過程
大體上的流程就是這樣。
1.目標(biāo):
這篇記錄debug 追溯源碼的過程,大概分三個篇幅,這是第一篇,現(xiàn)整體了解一下運行流程,定位資源加載,資源解析,bean 注冊發(fā)生的位置。
2. 記錄結(jié)構(gòu):
1.調(diào)試棧截圖
2.整體流程
3.bean.xml的處理
每段代碼下面有相應(yīng)的講解
每個棧幀中方法的行號都有標(biāo)明,按照行號追溯源碼,然后配合教程能夠快速學(xué)習(xí)。
ioc容器實例化代碼
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
進入代碼中一步步追溯,發(fā)現(xiàn)重要方法:refresh();
如下所示:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
//beanFactory實例化方法 單步調(diào)試入口
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
首先這個方法是同步的,以避免重復(fù)刷新。然后刷新的每個步驟,都放在單獨的方法里,比較清晰,可以按順序一個個看
首先是prepareRefresh()方法
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
synchronized (this.activeMonitor) {
this.active = true;
}
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
// Initialize any placeholder property sources in the context environment
initPropertySources();
// Validate that all properties marked as required are resolvable
// see ConfigurablePropertyResolver#setRequiredProperties
this.environment.validateRequiredProperties();
}
這個方法里做的事情不多,記錄了開始時間,輸出日志,另外initPropertySources()方法和validateRequiredProperties()方法一般都沒有做什么事。
然后是核心的obtainFreshBeanFactory()方法,這個方法是初始化BeanFactory,是整個refresh()方法的核心,其中完成了配置文件的加載、解析、注冊,后面會專門詳細說 。
這里要說明一下,ApplicationContext實現(xiàn)了BeanFactory接口,并實現(xiàn)了ResourceLoader、MessageSource等接口,可以認為是增強的BeanFactory。但是ApplicationContext并不自己重復(fù)實現(xiàn)BeanFactory定義的方法,而是委托給DefaultListableBeanFactory來實現(xiàn)。這種設(shè)計思路也是值得學(xué)習(xí)的。
后面的 prepareBeanFactory()、postProcessBeanFactory()、invokeBeanFactoryPostProcessors()、registerBeanPostProcessors()、initMessageSource()、initApplicationEventMulticaster()、onRefresh()、registerListeners()、finishBeanFactoryInitialization()、finishRefresh()等方法,是添加一些后處理器、廣播、攔截器等,就不一個個細說了
其中的關(guān)鍵方法是finishBeanFactoryInitialization(),在這個方法中,會對剛才注冊的Bean(不延遲加載的),進行實例化,所以也是一個核心方法。
從整體上介紹完了流程,接下來就重點看obtainFreshBeanFactory()方法,上文說到,在這個方法里,完成了配置文件的加載、解析、注冊
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
這個方法做了2件事,首先通過refreshBeanFactory()方法,創(chuàng)建了DefaultListableBeanFactory的實例,并進行初始化。
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);
}
}
首先如果已經(jīng)有BeanFactory實例,就先清空。然后通過createBeanFactory()方法,創(chuàng)建一個DefaultListableBeanFactory的實例
protected DefaultListableBeanFactory createBeanFactory() {
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
接下來設(shè)置ID唯一標(biāo)識
beanFactory.setSerializationId(getId());
然后允許用戶進行一些自定義的配置
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
beanFactory.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
}
最后,就是核心的loadBeanDefinitions()方法
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);
}
這里首先會創(chuàng)建一個XmlBeanDefinitionReader的實例,然后進行初始化。這個XmlBeanDefinitionReader中其實傳遞的BeanDefinitionRegistry類型的實例,為什么可以傳遞一個beanFactory呢,因為DefaultListableBeanFactory實現(xiàn)了BeanDefinitionRegistry接口,這里是多態(tài)的使用。
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);
}
這里要說明一下,ApplicationContext并不自己負責(zé)配置文件的加載、解析、注冊,而是將這些工作委托給XmlBeanDefinitionReader來做。
loadBeanDefinitions(beanDefinitionReader);
這行代碼,就是Bean定義讀取實際發(fā)生的地方。這里的工作,主要是XmlBeanDefinitionReader來完成的,下一篇博客會詳細介紹這個過程。
入口是loadBeanDefinitions方法
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader)
throws IOException {
String[] configLocations = getConfigLocations();
if (configLocations != null) {
for (String configLocation : configLocations) {
reader.loadBeanDefinitions(configLocation);
}
}
}
這是解析過程最外圍的代碼,首先要獲取到配置文件的路徑,這在之前已經(jīng)完成了。
然后將每個配置文件的路徑,作為參數(shù)傳給BeanDefinitionReader的loadBeanDefinitions方法里
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
}
這個方法又調(diào)用了重載方法
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;
}
}
首先getResourceLoader()的實現(xiàn)的前提條件是因為XmlBeanDefinitionReader在實例化的時候已經(jīng)確定了創(chuàng)建了實例ResourceLoader實例, 代碼位于 AbstractBeanDefinitionReader
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
// Determine ResourceLoader to use.
if (this.registry instanceof ResourceLoader) {
this.resourceLoader = (ResourceLoader) this.registry;
} else {
this.resourceLoader = new PathMatchingResourcePatternResolver();
}
// Inherit Environment if possible
if (this.registry instanceof EnvironmentCapable) {
this.environment = ((EnvironmentCapable)this.registry).getEnvironment();
} else {
this.environment = new StandardEnvironment();
}
}
這個方法比較長,BeanDefinitionReader不能直接加載配置文件,需要把配置文件封裝成Resource,然后才能調(diào)用重載方法loadBeanDefinitions()。所以這個方法其實就是2段,第一部分是委托ResourceLoader將配置文件封裝成Resource,第二部分是調(diào)用loadBeanDefinitions(),對Resource進行解析
而這里的ResourceLoader,就是前面的XmlWebApplicationContext,因為ApplicationContext接口,是繼承自ResourceLoader接口的
Resource也是一個接口體系,在web環(huán)境下,這里就是ServletContextResource
接下來進入重載方法loadBeanDefinitions()
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int counter = 0;
for (Resource resource : resources) {
counter += loadBeanDefinitions(resource);
}
return counter;
}
這里就不用說了,就是把每一個Resource作為參數(shù),繼續(xù)調(diào)用重載方法。讀spring源碼,會發(fā)現(xiàn)重載方法特別多。
public int loadBeanDefinitions(Resource resource) throws
BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
還是重載方法,不過這里對傳進來的Resource又進行了一次封裝,變成了編碼后的Resource。
public int loadBeanDefinitions(EncodedResource encodedResource)
throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
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();
}
}
}
這個就是loadBeanDefinitions()的最后一個重載方法,比較長,可以拆看來看。
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from " + encodedResource.getResource());
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<EncodedResource>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
這第一部分,是處理線程相關(guān)的工作,把當(dāng)前正在解析的Resource,設(shè)置為當(dāng)前Resource。
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();
}
}
這里是第二部分,是核心,首先把Resource還原為InputStream,然后調(diào)用實際解析的方法doLoadBeanDefinitions()。
可以看到,這種命名方式是很值得學(xué)習(xí)的,一種業(yè)務(wù)方法,比如parse(),可能需要做一些外圍的工作,然后實際解析的方法,可以命名為doParse()。這種doXXX()的命名方法,在很多開源框架中都有應(yīng)用,比如logback等。
接下來就看一下這個doLoadBeanDefinitions()方法
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
Document doc = doLoadDocument(inputSource, resource);return registerBeanDefinitions(doc, resource);
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
拋開異常處理:核心代碼如下:
Document doc = doLoadDocument(inputSource, resource);
return registerBeanDefinitions(doc, resource);
doLoadDocument方法將InputStream讀取成標(biāo)準(zhǔn)的Document對象,然后調(diào)用registerBeanDefinitions(),進行解析工作。
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
return this.documentLoader.loadDocument(inputSource,
getEntityResolver(), this.errorHandler,
getValidationModeForResource(resource),
isNamespaceAware());
}
接下來就看一下這個核心方法registerBeanDefinitions
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//創(chuàng)建的其實是DefaultBeanDefinitionDocumentReader 的實例,利用反射創(chuàng)建的。
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
documentReader.setEnvironment(this.getEnvironment());
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
這里注意兩點 :
1.Document對象
首先這個Document對象,是W3C定義的標(biāo)準(zhǔn)XML對象,跟spring無關(guān)。其次這個registerBeanDefinitions方法,我覺得命名有點誤導(dǎo)性。因為這個時候?qū)嶋H上解析還沒有開始,怎么直接就注冊了呢。比較好的命名,我覺得可以是parseAndRegisterBeanDefinitions()。
2.documentReader的創(chuàng)建時使用反射創(chuàng)建的,代碼如下
protected BeanDefinitionDocumentReader
createBeanDefinitionDocumentReader() {
return BeanDefinitionDocumentReader.class.cast(BeanUtils.
instantiateClass(this.documentReaderClass));
}
instantiateClass方法中傳入了一個Class類型的參數(shù)。追溯發(fā)現(xiàn)下述代碼:
private Class<?> documentReaderClass =
DefaultBeanDefinitionDocumentReader.class;
所以創(chuàng)建的documentReaderClass是DefaultBeanDefinitionDocumentReader類的實例。
接下來就進入BeanDefinitionDocumentReader 中定義的registerBeanDefinitions()方法看看
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}
處理完外圍事務(wù)之后,進入doRegisterBeanDefinitions()方法,這種命名規(guī)范,上文已經(jīng)介紹過了
protected void doRegisterBeanDefinitions(Element root) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
Assert.state(this.environment != null, "environment property must not be null");
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!this.environment.acceptsProfiles(specifiedProfiles)) {
return;
}
}
// any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createHelper(readerContext, root, parent);
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
這個方法也比較長,拆開來看
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
Assert.state(this.environment != null, "environment property must not be null");
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!this.environment.acceptsProfiles(specifiedProfiles)) {
return;
}
}
如果配置文件中元素,配有profile屬性,就會進入這一段,不過一般都是不會的
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createHelper(readerContext, root, parent);
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
然后這里創(chuàng)建了BeanDefinitionParserDelegate對象,preProcessXml()和postProcessXml()都是空方法,核心就是parseBeanDefinitions()方法。這里又把BeanDefinition解析和注冊的工作,委托給了BeanDefinitionParserDelegate對象,在parseBeanDefinitions()方法中完成
總的來說,解析工作的委托鏈?zhǔn)沁@樣的:ClassPathXmlApplicationContext,XmlBeanDefinitionReader,DefaultBeanDefinitionDocumentReader,BeanDefinitionParserDelegate
ClassPathXmlApplicationContext作為最外圍的組件,發(fā)起解析的請求
XmlBeanDefinitionReader將配置文件路徑封裝為Resource,讀取出w3c定義的Document對象,然后委托給DefaultBeanDefinitionDocumentReader
DefaultBeanDefinitionDocumentReader就開始做實際的解析工作了,但是涉及到bean的具體解析,它還是會繼續(xù)委托給BeanDefinitionParserDelegate來做。
接下來在parseBeanDefinitions()方法中發(fā)生了什么,以及BeanDefinitionParserDelegate類完成的工作,在下一篇博客中繼續(xù)介紹。
BeanDefinition的解析,已經(jīng)走到了DefaultBeanDefinitionDocumentR
eader里,這時候配置文件已經(jīng)被加載,并解析成w3c的Document對象。這篇博客就接著介紹,DefaultBeanDefinitionDocumentReader和BeanDefinitionParserDelegate類,是怎么協(xié)同完成bean的解析和注冊的。
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createHelper(readerContext, root, parent);
preProcessXml(root);
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
這段代碼,創(chuàng)建了一個BeanDefinitionParserDelegate組件,然后就是preProcessXml()、parseBeanDefinitions()、postProcessXml()方法
其中preProcessXml()和postProcessXml()默認是空方法,接下來就看下parseBeanDefinitions()方法
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
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);
}
}
從這個方法開始,BeanDefinitionParserDelegate就開始發(fā)揮作用了,判斷當(dāng)前解析元素是否屬于默認的命名空間,如果是的話,就調(diào)用parseDefaultElement()方法,否則調(diào)用delegate上parseCustomElement()方法
public boolean isDefaultNamespace(String namespaceUri) {
return (!StringUtils.hasLength(namespaceUri) || BEANS_NAMESPACE_URI.equals(namespaceUri));
}
public boolean isDefaultNamespace(Node node) {
return isDefaultNamespace(getNamespaceURI(node));
}
只有
http://www.springframework.org/schema/beans,會被認為是默認的命名空間。也就是說,beans、bean這些元素,會認為屬于默認的命名空間,而像task:scheduled這些,就認為不屬于默認命名空間。
根節(jié)點beans的一個子節(jié)點bean,是屬于默認命名空間的,所以會進入parseDefaultElement()方法
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);
}
}
這里可能會有4種情況,import、alias、bean、beans,分別有一個方法與之對應(yīng),這里解析的是bean元素,所以會進入processBeanDefinition()方法
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));
}
}
這里主要有3個步驟,先是委托delegate對bean進行解析,然后委托delegate對bean進行裝飾,最后由一個工具類來完成BeanDefinition的注冊
可以看出來,DefaultBeanDefinitionDocumentReader不負責(zé)任何具體的bean解析,它面向的是xml Document對象,根據(jù)其元素的命名空間和名稱,起一個類似路由的作用(不過,命名空間的判斷,也是委托給delegate來做的)。所以這個類的命名,是比較貼切的,突出了其面向Document的特性。具體的工作,是由BeanDefinitionParserDelegate來完成的
下面就看下parseBeanDefinitionElement()方法
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<String>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() && !this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
這個方法很長,可以分成三段來看
String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<String>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
這一段,主要是處理一些跟alias,id等標(biāo)識相關(guān)的東西
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
這一行是核心,進行實際的解析
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
這段是后置處理,對beanName進行處理
前置處理和后置處理,不是核心,就不細看了,重點看下核心的那一行調(diào)用
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, BeanDefinition containingBean) {
this.parseState.push(new BeanEntry(beanName));
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
try {
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
parseMetaElements(ele, bd);
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
parseConstructorArgElements(ele, bd);
parsePropertyElements(ele, bd);
parseQualifierElements(ele, bd);
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
}
catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}
return null;
}
這個方法也挺長的,拆開看看
this.parseState.push(new BeanEntry(beanName));
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
這段是從配置中抽取出類名。接下來的長長一段,把異常處理先拋開,看看實際的業(yè)務(wù)
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
parseMetaElements(ele, bd);
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
parseConstructorArgElements(ele, bd);
parsePropertyElements(ele, bd);
parseQualifierElements(ele, bd);
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
這里每個方法的命名,就說明了是要干什么,可以一個個跟進去看,本文就不細說了。總之,經(jīng)過這里的解析,就得到了一個完整的BeanDefinitionHolder。只是說明一下,如果在配置文件里,沒有對一些屬性進行設(shè)置,比如autowire-candidate等,那么這個解析生成的BeanDefinition,都會得到一個默認值
然后,對這個Bean做一些必要的裝飾
public BeanDefinitionHolder decorateBeanDefinitionIfRequired(
Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd) {
BeanDefinitionHolder finalDefinition = definitionHolder;
// Decorate based on custom attributes first.
NamedNodeMap attributes = ele.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
}
// Decorate based on custom nested elements.
NodeList children = ele.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
}
}
return finalDefinition;
}
持續(xù)單步調(diào)試,代碼繼續(xù)運行到DefaultBeanDefinitionDocumentReader中的processBeanDefinition中的registerBeanDefinition()
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder,
getReaderContext().getRegistry());
單步進入代碼發(fā)現(xiàn)BeanDefinitionReaderUtils靜態(tài)方法registerBeanDefinition()
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
// 其實調(diào)用的是DefaultListableBeanFactory中的registerBeanDefinition方法
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String aliase : aliases) {
registry.registerAlias(beanName, aliase);
}
}
}
解釋一下
其實調(diào)用的是DefaultListableBeanFactory中的registerBeanDefinition方法這句話,因為DefaultListableBeanFactory實現(xiàn)BeanDefinitionRegistry接口,BeanDefinitionRegistry接口中定義了registerBeanDefinition()方法
看下DefaultListableBeanFactory中registerBeanDefinition()實例方法的具體實現(xiàn):
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);
}
}
synchronized (this.beanDefinitionMap) {
Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
if (oldBeanDefinition != null) {
if (!this.allowBeanDefinitionOverriding) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already [" + oldBeanDefinition + "] bound.");
}
else {
if (this.logger.isInfoEnabled()) {
this.logger.info("Overriding bean definition for bean '" + beanName +
"': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
}
}
}
else {
this.beanDefinitionNames.add(beanName);
this.frozenBeanDefinitionNames = null;
}
this.beanDefinitionMap.put(beanName, beanDefinition);
resetBeanDefinition(beanName);
}
}
代碼追溯之后發(fā)現(xiàn)這個方法里,最關(guān)鍵的是以下2行:
this.beanDefinitionNames.add(beanName);
this.beanDefinitionMap.put(beanName, beanDefinition);
前者是把beanName放到隊列里,后者是把BeanDefinition放到map中,到此注冊就完成了。在后面實例化的時候,就是把beanDefinitionMap中的BeanDefinition取出來,逐一實例化
BeanFactory準(zhǔn)備完畢之后,代碼又回到了ClassPathXmlApplicationContext里
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}
也就是obtainFreshBeanFactory()方法執(zhí)行之后,再進行下面的步驟。
總結(jié)來說,ApplicationContext將解析配置文件的工作委托給BeanDefinitionReader,然后BeanDefinitionReader將配置文件讀取為xml的Document文檔之后,又委托給BeanDefinitionDocumentReader
BeanDefinitionDocumentReader這個組件是根據(jù)xml元素的命名空間和元素名,起到一個路由的作用,實際的解析工作,是委托給BeanDefinitionParserDelegate來完成的。
BeanDefinitionParserDelegate的解析工作完成以后,會返回BeanDefinitionHolder給BeanDefinitionDocumentReader,在這里,會委托給DefaultListableBeanFactory完成bean的注冊
XmlBeanDefinitionReader(計數(shù)、解析XML文檔),BeanDefinitionDocumentReader(依賴xml文檔,進行解析和注冊),BeanDefinitionParserDelegate(實際的解析工作)。
可以看出,在解析bean的過程中,這3個組件的分工是比較清晰的,各司其職,這種設(shè)計思想值得學(xué)習(xí)
到此為止,bean的解析、注冊、spring ioc 容器的實例化過程就基本分析結(jié)束了。
網(wǎng)頁題目:Spring源碼剖析3:SpringIOC容器的加載過程
標(biāo)題來源:http://jinyejixie.com/article2/psieoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、小程序開發(fā)、企業(yè)網(wǎng)站制作、品牌網(wǎng)站制作、軟件開發(fā)、品牌網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)