Spring體系的各種啟動流程詳解
在介紹spring的啟動之前,先來說下啟動過程中使用到的幾個類
基本組件
1、BeanFactory:spring底層容器,定義了最基本的容器功能,注意區(qū)分FactoryBean
2、ApplicationContext:擴展于BeanFactory,擁有更豐富的功能。例如:添加事件發(fā)布機制、父子級容器,一般都是直接使用ApplicationContext。
3、Resource:bean配置文件,一般為xml文件??梢岳斫鉃楸4鎎ean信息的文件。
4、BeanDefinition:beandifinition定義了bean的基本信息,根據(jù)它來創(chuàng)造bean
基礎流程
不管是哪種系列的spring(springframework、springmvc、springboot、springcloud),Spring的啟動過程主要可以分為兩部分:
第一步:解析成BeanDefinition:將bean定義信息解析為BeanDefinition類,不管bean信息是定義在xml中,還是通過@Bean注解標注,都能通過不同的BeanDefinitionReader轉為BeanDefinition類,將BeanDefinition向Map中注冊 Map<name,beandefinition>。這里分兩種BeanDefinition,RootBeanDefintion和BeanDefinition。RootBeanDefinition這種是系統(tǒng)級別的,是啟動Spring必須加載的6個Bean。BeanDefinition是我們定義的Bean。
第二步:參照BeanDefintion定義的類信息,通過BeanFactory生成bean實例存放在緩存中。這里的BeanFactoryPostProcessor是一個攔截器,在BeanDefinition實例化后,BeanFactory生成該Bean之前,可以對BeanDefinition進行修改。BeanFactory根據(jù)BeanDefinition定義使用反射實例化Bean,實例化和初始化Bean的過程中就涉及到Bean的生命周期了,典型的問題就是Bean的循環(huán)依賴。接著,Bean實例化前會判斷該Bean是否需要增強,并決定使用哪種代理來生成Bean。
Springframework
1、容器類
在一般性的spring項目中,大家應該也都知道,一般是通過直接實例化applicationContext類,來實現(xiàn)項目的啟動 下面我們來看下通過注解的方式來啟動的情況,注解容器定義如下:
public AnnotationConfigApplicationContext(Class<?>... componentClasses) { this(); register(componentClasses); refresh(); } public AnnotationConfigApplicationContext() { this.reader = new AnnotatedBeanDefinitionReader(this); this.scanner = new ClassPathBeanDefinitionScanner(this); }
創(chuàng)建了注解定義bean讀取器和配置文件定義bean掃描器
2、注解定義bean讀取器
進入該類構造器中,可以看到最終會執(zhí)行該方法:
public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors( BeanDefinitionRegistry registry, @Nullable Object source) { DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry); if (beanFactory != null) { if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) { beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE); } if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) { beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver()); } } Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8); if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)); } if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); } ... }
注冊了6個RootBeanDefinition,即系統(tǒng)級別的BeanDefinition。同時,經(jīng)過調(diào)用registerPostProcessor->registerBeanDefinition,可以看到注冊BeanDefinition其實就是放到BeanFactory的緩存中。
DefaultListableBeanFactory.java類中 public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { ... this.beanDefinitionMap.put(beanName, beanDefinition); ... }
上面的6個beanDefinition的實例參數(shù)中都有一個postprocessor后綴的類,我們分別點擊進入查看即繼承關系,可以看到,最終都繼承自``接口
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor { void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry var1) throws BeansException; } @FunctionalInterface public interface BeanFactoryPostProcessor { void postProcessBeanFactory(ConfigurableListableBeanFactory var1) throws BeansException; }
3、BeanFactoryPostProcessor
1、BeanFactoryPostProcessor是spring初始化bean的擴展點。
官文翻譯如下:允許自定義修改應用程序上下文的bean定義,調(diào)整上下文的基礎bean工廠的bean屬性值。應用程序上下文可以在其bean定義中自動檢測BeanFactoryPostProcessor bean,并在創(chuàng)建任何其他bean之前先創(chuàng)建BeanFactoryPostProcessor。
BeanFactoryPostProcessor可以與bean定義交互并修改bean定義,但絕不能與bean實例交互。這樣做可能會導致bean過早實例化,違反容器并導致意外的副作用。如果需要bean實例交互,請考慮實現(xiàn)BeanPostProcessor。實現(xiàn)該接口,可以允許我們的程序獲取到BeanFactory,從而修改BeanFactory,可以實現(xiàn)編程式的往Spring容器中添加Bean。
也就是說,我們可以通過實現(xiàn)BeanFactoryPostProcessor接口,獲取BeanFactory,操作BeanFactory對象,修改BeanDefinition,但不要去實例化bean。
2、BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子類,在父類的基礎上,增加了新的方法,允許我們獲取到BeanDefinitionRegistry,從而編碼動態(tài)修改BeanDefinition。
例如往BeanDefinition中添加一個新的BeanDefinition。
這兩個接口是在AbstractApplicationContext#refresh方法中執(zhí)行到invokeBeanFactoryPostProcessors(beanFactory);方法時被執(zhí)行的。
3、示例代碼如下:
@Repository public class OrderDao { public void query() { System.out.println("OrderDao query..."); } } public class OrderService { private OrderDao orderDao; public void setDao(OrderDao orderDao) { this.orderDao = orderDao; } public void init() { System.out.println("OrderService init..."); } public void query() { orderDao.query(); } } @Component public class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { //向Spring容器中注冊OrderService BeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(OrderService.class) //這里的屬性名是根據(jù)setter方法 .addPropertyReference("dao", "orderDao") .setInitMethodName("init") .setScope(BeanDefinition.SCOPE_SINGLETON) .getBeanDefinition(); registry.registerBeanDefinition("orderService", beanDefinition); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { // 在這里修改orderService bean的scope為PROTOTYPE BeanDefinition beanDefinition = beanFactory.getBeanDefinition("orderService"); beanDefinition.setScope(BeanDefinition.SCOPE_PROTOTYPE); } }
回到上面,我們拿ConfigurationClassPostProcessor來說:在Spring中ConfigurationClassPostProcessor同時實現(xiàn)了BeanDefinitionRegistryPostProcessor接口和其父類接口中的方法。
1、ConfigurationClassPostProcessor#postProcessBeanFactory:主要負責對Full Configuration 配置進行增強,攔截@Bean方法來確保增強執(zhí)行@Bean方法的語義。
2、ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry:負責掃描我們的程序,根據(jù)程序的中Bean創(chuàng)建BeanDefinition,并注冊到容器中。
我們進入到:
private void loadBeanDefinitionsForConfigurationClass( ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) { if (trackedConditionEvaluator.shouldSkip(configClass)) { String beanName = configClass.getBeanName(); if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) { this.registry.removeBeanDefinition(beanName); } this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName()); return; } if (configClass.isImported()) { registerBeanDefinitionForImportedConfigurationClass(configClass); } for (BeanMethod beanMethod : configClass.getBeanMethods()) { loadBeanDefinitionsForBeanMethod(beanMethod); } loadBeanDefinitionsFromImportedResources(configClass.getImportedResources()); loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars()); }
其中,我們可以看到:
1、通過檢查是否有·@import·注解,來注冊該導入類到容器中
if (configClass.isImported()) { registerBeanDefinitionForImportedConfigurationClass(configClass); }
2、遍歷@Configuration類中的@bean注解,將其類注冊到容器中
if (configClass.isImported()) { registerBeanDefinitionForImportedConfigurationClass(configClass); }
4、refresh
這個方法就是正式進行bean的處理的主要邏輯
@Override 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) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
前面說的一些擴展點類都是在這里才處理的,spring的擴展機制后面會有專門的文章來講解。
SpringMVC
而在web項目中,我們一般都是使用的spring mvc,Spring Framework本身沒有Web功能,Spring MVC使用WebApplicationContext類擴展ApplicationContext,使得擁有web功能。
那么,Spring MVC是如何在web環(huán)境中創(chuàng)建IoC容器呢?web環(huán)境中的IoC容器的結構又是什么結構呢?web環(huán)境中,Spring IoC容器是怎么啟動呢?
1、配置
以Tomcat為例,在Web容器中使用Spirng MVC,必須進行四項的配置:
修改web.xml,添加servlet定義;
編寫servletname-servlet.xml(servletname是在web.xm中配置DispactherServlet時使servlet-name的值)配置;
contextConfigLocation初始化參數(shù)
配置ContextLoaderListerner;示例配置如下:
<!-- servlet定義:前端處理器,接受的HTTP請求和轉發(fā)請求的類 --> <servlet> <servlet-name>court</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <!-- court-servlet.xml:定義WebAppliactionContext上下文中的bean --> <param-name>contextConfigLocation</param-name> <param-value>classpath*:court-servlet.xml</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>court</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置contextConfigLocation初始化參數(shù):指定Spring IoC容器需要讀取的定義了非web層的Bean(DAO/Service)的XML文件路徑 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/court-service.xml</param-value> </context-param> <!-- 配置ContextLoaderListerner:Spring MVC在Web容器中的啟動類,負責Spring IoC容器在Web上下文中的初始化 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
在web.xml配置文件中,有兩個主要的配置:ContextLoaderListener和DispatcherServlet。
同樣的關于spring配置文件的相關配置也有兩部分:context-param和DispatcherServlet中的init-param。
那么,這兩部分的配置有什么區(qū)別呢?它們都擔任什么樣的職責呢?
在Spring MVC中,Spring Context是以父子的繼承結構存在的。
Web環(huán)境中存在一個ROOT Context,這個Context是整個應用的根上下文,是其他context的雙親Context。
同時Spring MVC也對應的持有一個獨立的Context,它是ROOT Context的子上下文。
對于這樣的Context結構在Spring MVC中是如何實現(xiàn)的呢?下面就先從ROOT Context入手,ROOT Context是在ContextLoaderListener中配置的,ContextLoaderListener讀取context-param中的contextConfigLocation指定的配置文件,創(chuàng)建ROOT Context。
2、啟動過程
Spring MVC啟動過程大致分為兩個過程:
- ContextLoaderListener初始化,實例化IoC容器,并將此容器實例注冊到ServletContext中;
- DispatcherServlet初始化;
tomcat在啟動的時候,會依次執(zhí)行l(wèi)isteners的初始化,也就是執(zhí)行該ContextLoaderListener的初始化,最終會調(diào)用下面的代碼:
public void contextInitialized(ServletContextEvent event) { this.initWebApplicationContext(event.getServletContext()); } public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { //PS : ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE=WebApplicationContext.class.getName() + ".ROOT" 根上下文的名稱 //PS : 默認情況下,配置文件的位置和名稱是:DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml" //在整個web應用中,只能有一個根上下文 if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException("Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { // 在這里執(zhí)行了創(chuàng)建WebApplicationContext的操作 this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } } // PS: 將根上下文放置在servletContext中 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; } }
我們注意到這樣一句configureAndRefreshWebApplicationContext(cwac, servletContext); 這個就是具體創(chuàng)建容器的方法,我們進入去看看
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -> assign a more useful id based on available information String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); if (idParam != null) { wac.setId(idParam); } else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(sc.getContextPath())); } } wac.setServletContext(sc); String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); if (configLocationParam != null) { wac.setConfigLocation(configLocationParam); } // The wac environment's #initPropertySources will be called in any case when the context // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); } customizeContext(sc, wac); wac.refresh(); }
我們注意到wac.refresh();看起來是不是有點熟悉了,進入看看:
public final void refresh() throws BeansException, IllegalStateException { try { super.refresh(); } catch (RuntimeException ex) { WebServer webServer = this.webServer; if (webServer != null) { webServer.stop(); } throw ex; } }
這里的super根據(jù)繼承關系,我們知道,最終就是進入到了springframework中的refresh中,這個方法我們在上面已經(jīng)說過了。
SpringBoot
啟動入口方法如下:
public static void main(String[] args) { SpringApplication.run(ConsulApplication.class, args); }
通過代碼的層層調(diào)用,最終會走到這樣的代碼中:
public ConfigurableApplicationContext run(String... args) { StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList(); this.configureHeadlessProperty(); SpringApplicationRunListeners listeners = this.getRunListeners(args); listeners.starting(); Collection exceptionReporters; try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments); this.configureIgnoreBeanInfo(environment); Banner printedBanner = this.printBanner(environment); context = this.createApplicationContext(); exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context); this.prepareContext(context, environment, listeners, applicationArguments, printedBanner); this.refreshContext(context); this.afterRefresh(context, applicationArguments); stopWatch.stop(); if (this.logStartupInfo) { (new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch); } listeners.started(context); this.callRunners(context, applicationArguments); } catch (Throwable var10) { this.handleRunFailure(context, var10, exceptionReporters, listeners); throw new IllegalStateException(var10); } try { listeners.running(context); return context; } catch (Throwable var9) { this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null); throw new IllegalStateException(var9); } }
可以看到,又走到了大家都熟悉的spring啟動代碼里面去了。
綜上:可以看出,不管是哪種系列的spring,最終都會走到spring基本的啟動流程中,無非就是根據(jù)自己的特性需要加了一些額外的處理罷了。
總結
到此這篇關于Spring體系的各種啟動流程的文章就介紹到這了,更多相關Spring啟動流程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Boot前后端分離開發(fā)模式中的跨域問題及解決方法
本文介紹了解決Spring Boot前端Vue跨域問題的實戰(zhàn)經(jīng)驗,并提供了后端和前端的配置示例,通過配置后端和前端,我們可以輕松解決跨域問題,實現(xiàn)正常的前后端交互,需要的朋友可以參考下2023-09-09Springboot?接口需要接收參數(shù)類型是數(shù)組問題
這篇文章主要介紹了Springboot?接口需要接收參數(shù)類型是數(shù)組問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01