Spring體系的各種啟動(dòng)流程詳解
在介紹spring的啟動(dòng)之前,先來說下啟動(dòng)過程中使用到的幾個(gè)類
基本組件
1、BeanFactory:spring底層容器,定義了最基本的容器功能,注意區(qū)分FactoryBean
2、ApplicationContext:擴(kuò)展于BeanFactory,擁有更豐富的功能。例如:添加事件發(fā)布機(jī)制、父子級容器,一般都是直接使用ApplicationContext。
3、Resource:bean配置文件,一般為xml文件??梢岳斫鉃楸4鎎ean信息的文件。
4、BeanDefinition:beandifinition定義了bean的基本信息,根據(jù)它來創(chuàng)造bean
基礎(chǔ)流程
不管是哪種系列的spring(springframework、springmvc、springboot、springcloud),Spring的啟動(dòng)過程主要可以分為兩部分:
第一步:解析成BeanDefinition:將bean定義信息解析為BeanDefinition類,不管bean信息是定義在xml中,還是通過@Bean注解標(biāo)注,都能通過不同的BeanDefinitionReader轉(zhuǎn)為BeanDefinition類,將BeanDefinition向Map中注冊 Map<name,beandefinition>。這里分兩種BeanDefinition,RootBeanDefintion和BeanDefinition。RootBeanDefinition這種是系統(tǒng)級別的,是啟動(dòng)Spring必須加載的6個(gè)Bean。BeanDefinition是我們定義的Bean。
第二步:參照BeanDefintion定義的類信息,通過BeanFactory生成bean實(shí)例存放在緩存中。這里的BeanFactoryPostProcessor是一個(gè)攔截器,在BeanDefinition實(shí)例化后,BeanFactory生成該Bean之前,可以對BeanDefinition進(jìn)行修改。BeanFactory根據(jù)BeanDefinition定義使用反射實(shí)例化Bean,實(shí)例化和初始化Bean的過程中就涉及到Bean的生命周期了,典型的問題就是Bean的循環(huán)依賴。接著,Bean實(shí)例化前會判斷該Bean是否需要增強(qiáng),并決定使用哪種代理來生成Bean。
Springframework
1、容器類
在一般性的spring項(xiàng)目中,大家應(yīng)該也都知道,一般是通過直接實(shí)例化applicationContext類,來實(shí)現(xiàn)項(xiàng)目的啟動(dòng) 下面我們來看下通過注解的方式來啟動(dòng)的情況,注解容器定義如下:
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讀取器
進(jìn)入該類構(gòu)造器中,可以看到最終會執(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個(gè)RootBeanDefinition,即系統(tǒng)級別的BeanDefinition。同時(shí),經(jīng)過調(diào)用registerPostProcessor->registerBeanDefinition,可以看到注冊BeanDefinition其實(shí)就是放到BeanFactory的緩存中。
DefaultListableBeanFactory.java類中 public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) throws BeanDefinitionStoreException { ... this.beanDefinitionMap.put(beanName, beanDefinition); ... }
上面的6個(gè)beanDefinition的實(shí)例參數(shù)中都有一個(gè)postprocessor后綴的類,我們分別點(diǎn)擊進(jìn)入查看即繼承關(guān)系,可以看到,最終都繼承自``接口
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的擴(kuò)展點(diǎn)。
官文翻譯如下:允許自定義修改應(yīng)用程序上下文的bean定義,調(diào)整上下文的基礎(chǔ)bean工廠的bean屬性值。應(yīng)用程序上下文可以在其bean定義中自動(dòng)檢測BeanFactoryPostProcessor bean,并在創(chuàng)建任何其他bean之前先創(chuàng)建BeanFactoryPostProcessor。
BeanFactoryPostProcessor可以與bean定義交互并修改bean定義,但絕不能與bean實(shí)例交互。這樣做可能會導(dǎo)致bean過早實(shí)例化,違反容器并導(dǎo)致意外的副作用。如果需要bean實(shí)例交互,請考慮實(shí)現(xiàn)BeanPostProcessor。實(shí)現(xiàn)該接口,可以允許我們的程序獲取到BeanFactory,從而修改BeanFactory,可以實(shí)現(xiàn)編程式的往Spring容器中添加Bean。
也就是說,我們可以通過實(shí)現(xiàn)BeanFactoryPostProcessor接口,獲取BeanFactory,操作BeanFactory對象,修改BeanDefinition,但不要去實(shí)例化bean。
2、BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子類,在父類的基礎(chǔ)上,增加了新的方法,允許我們獲取到BeanDefinitionRegistry,從而編碼動(dòng)態(tài)修改BeanDefinition。
例如往BeanDefinition中添加一個(gè)新的BeanDefinition。
這兩個(gè)接口是在AbstractApplicationContext#refresh方法中執(zhí)行到invokeBeanFactoryPostProcessors(beanFactory);方法時(shí)被執(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容器中注冊O(shè)rderService 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同時(shí)實(shí)現(xiàn)了BeanDefinitionRegistryPostProcessor接口和其父類接口中的方法。
1、ConfigurationClassPostProcessor#postProcessBeanFactory:主要負(fù)責(zé)對Full Configuration 配置進(jìn)行增強(qiáng),攔截@Bean方法來確保增強(qiáng)執(zhí)行@Bean方法的語義。
2、ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry:負(fù)責(zé)掃描我們的程序,根據(jù)程序的中Bean創(chuàng)建BeanDefinition,并注冊到容器中。
我們進(jìn)入到:
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·注解,來注冊該導(dǎo)入類到容器中
if (configClass.isImported()) { registerBeanDefinitionForImportedConfigurationClass(configClass); }
2、遍歷@Configuration類中的@bean注解,將其類注冊到容器中
if (configClass.isImported()) { registerBeanDefinitionForImportedConfigurationClass(configClass); }
4、refresh
這個(gè)方法就是正式進(jìn)行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(); } } }
前面說的一些擴(kuò)展點(diǎn)類都是在這里才處理的,spring的擴(kuò)展機(jī)制后面會有專門的文章來講解。
SpringMVC
而在web項(xiàng)目中,我們一般都是使用的spring mvc,Spring Framework本身沒有Web功能,Spring MVC使用WebApplicationContext類擴(kuò)展ApplicationContext,使得擁有web功能。
那么,Spring MVC是如何在web環(huán)境中創(chuàng)建IoC容器呢?web環(huán)境中的IoC容器的結(jié)構(gòu)又是什么結(jié)構(gòu)呢?web環(huán)境中,Spring IoC容器是怎么啟動(dòng)呢?
1、配置
以Tomcat為例,在Web容器中使用Spirng MVC,必須進(jìn)行四項(xiàng)的配置:
修改web.xml,添加servlet定義;
編寫servletname-servlet.xml(servletname是在web.xm中配置DispactherServlet時(shí)使servlet-name的值)配置;
contextConfigLocation初始化參數(shù)
配置ContextLoaderListerner;示例配置如下:
<!-- servlet定義:前端處理器,接受的HTTP請求和轉(zhuǎn)發(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容器中的啟動(dòng)類,負(fù)責(zé)Spring IoC容器在Web上下文中的初始化 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
在web.xml配置文件中,有兩個(gè)主要的配置:ContextLoaderListener和DispatcherServlet。
同樣的關(guān)于spring配置文件的相關(guān)配置也有兩部分:context-param和DispatcherServlet中的init-param。
那么,這兩部分的配置有什么區(qū)別呢?它們都擔(dān)任什么樣的職責(zé)呢?
在Spring MVC中,Spring Context是以父子的繼承結(jié)構(gòu)存在的。
Web環(huán)境中存在一個(gè)ROOT Context,這個(gè)Context是整個(gè)應(yīng)用的根上下文,是其他context的雙親Context。
同時(shí)Spring MVC也對應(yīng)的持有一個(gè)獨(dú)立的Context,它是ROOT Context的子上下文。
對于這樣的Context結(jié)構(gòu)在Spring MVC中是如何實(shí)現(xiàn)的呢?下面就先從ROOT Context入手,ROOT Context是在ContextLoaderListener中配置的,ContextLoaderListener讀取context-param中的contextConfigLocation指定的配置文件,創(chuàng)建ROOT Context。
2、啟動(dòng)過程
Spring MVC啟動(dòng)過程大致分為兩個(gè)過程:
- ContextLoaderListener初始化,實(shí)例化IoC容器,并將此容器實(shí)例注冊到ServletContext中;
- DispatcherServlet初始化;
tomcat在啟動(dòng)的時(shí)候,會依次執(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 : 默認(rèn)情況下,配置文件的位置和名稱是:DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml" //在整個(gè)web應(yīng)用中,只能有一個(gè)根上下文 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); 這個(gè)就是具體創(chuàng)建容器的方法,我們進(jìn)入去看看
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();看起來是不是有點(diǎn)熟悉了,進(jìn)入看看:
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ù)繼承關(guān)系,我們知道,最終就是進(jìn)入到了springframework中的refresh中,這個(gè)方法我們在上面已經(jīng)說過了。
SpringBoot
啟動(dòng)入口方法如下:
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啟動(dòng)代碼里面去了。
綜上:可以看出,不管是哪種系列的spring,最終都會走到spring基本的啟動(dòng)流程中,無非就是根據(jù)自己的特性需要加了一些額外的處理罷了。
總結(jié)
到此這篇關(guān)于Spring體系的各種啟動(dòng)流程的文章就介紹到這了,更多相關(guān)Spring啟動(dòng)流程內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring Boot前后端分離開發(fā)模式中的跨域問題及解決方法
本文介紹了解決Spring Boot前端Vue跨域問題的實(shí)戰(zhàn)經(jīng)驗(yàn),并提供了后端和前端的配置示例,通過配置后端和前端,我們可以輕松解決跨域問題,實(shí)現(xiàn)正常的前后端交互,需要的朋友可以參考下2023-09-09關(guān)于Lombok @Data注解:簡化Java代碼的魔法棒
Lombok庫通過@Data注解自動(dòng)生成常見的樣板代碼如getter、setter、toString等,極大減少代碼量,提高開發(fā)效率,@Data注解集成了@ToString、@EqualsAndHashCode、@Getter、@Setter、@RequiredArgsConstructor等注解的功能2024-10-10WIN10系統(tǒng)中添加bat腳本重啟jar服務(wù)
在bat腳本中執(zhí)行java服務(wù),命令與cmd中類似,下面這篇文章主要給大家介紹了關(guān)于WIN10系統(tǒng)中添加bat腳本重啟jar服務(wù)的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12Springboot?接口需要接收參數(shù)類型是數(shù)組問題
這篇文章主要介紹了Springboot?接口需要接收參數(shù)類型是數(shù)組問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01