Spring Boot ( ) refresh

Spring Boot ( ) refresh

Spring -- refresh

refresh Spring Bean Spring

refresh

refresh

SpringApplication.run(String... args)

//SpringApplication # run(String... args) # 311-313 public ConfigurableApplicationContext run(String... args) { // prepareContext(context, environment, listeners, applicationArguments, printedBanner); refreshContext(context); afterRefresh(context, applicationArguments); // return context; }

refreshContext(context)

//SpringApplication # refreshContext(ConfigurableApplicationContext context) # 390 private void refreshContext(ConfigurableApplicationContext context) { refresh(context); if (this.registerShutdownHook) { try { context.registerShutdownHook(); } catch (AccessControlException ex) { //Not allowed in some environments. } } }

refresh(context)

//SpringApplication # refresh(ApplicationContext applicationContext) # 742 protected void refresh(ApplicationContext applicationContext) { Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext); ((AbstractApplicationContext) applicationContext).refresh(); }

((AbstractApplicationContext) applicationContext).refresh()

//AbstractApplicationContext # refresh() # 515 public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //Prepare this context for refreshing. // prepareRefresh(); //Tell the subclass to refresh the internal bean factory. // bean ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //Prepare the bean factory for use in this context. // bean prepareBeanFactory(beanFactory); try { //Allows post-processing of the bean factory in context subclasses. // bean postProcessBeanFactory(beanFactory); //Invoke factory processors registered as beans in the context. // bean invokeBeanFactoryPostProcessors(beanFactory); //Register bean processors that intercept bean creation. // Bean Bean registerBeanPostProcessors(beanFactory); //Initialize message source for this context. // initMessageSource(); //Initialize event multicaster for this context. // initApplicationEventMulticaster(); //Initialize other special beans in specific context subclasses. // bean onRefresh(); //Check for listener beans and register them. // registerListeners(); //Instantiate all remaining (non-lazy-init) singletons. // finishBeanFactoryInitialization(beanFactory); //Last step: publish corresponding event. // finishRefresh(); } // }

prepareRefresh

protected void prepareRefresh() { // this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); // //Initialize any placeholder property sources in the context environment. // initPropertySources(); //Validate that all properties marked as required are resolvable: //see ConfigurablePropertyResolver#setRequiredProperties // getEnvironment().validateRequiredProperties(); //Store pre-refresh ApplicationListeners... // if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { //Reset local application listeners to pre-refresh state. this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); } //Allow for the collection of early ApplicationEvents, //to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet<>(); }

obtainFreshBeanFactory

//AbstractApplicationContext # obtainFreshBeanFactory() # 635 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); return getBeanFactory(); }

  • beanFactory id
  • beanFacotory

prepareBeanFactory

obtainFreshBeanFactory()
beanFacotory

ClassLoader

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { //Tell the internal bean factory to use the context's class loader etc. // bean beanFactory.setBeanClassLoader(getClassLoader()); beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); //Configure the bean factory with context callbacks. // Bean beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); //BeanFactory interface not registered as resolvable type in a plain factory. //BeanFactory //MessageSource registered (and found for autowiring) as a bean. //MessageSource Bean beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this); //Register early post-processor for detecting inner beans as ApplicationListeners. // bean ApplicationListeners beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); //Detect a LoadTimeWeaver and prepare for weaving, if found. // LoadTimeWeaver if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); //Set a temporary ClassLoader for type matching. // ClassLoader beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } //Register default environment beans. // Bean if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }

  • beanFactory

postProcessBeanFactory(beanFactory)

beanFactory

Servlet request session

invokeBeanFactoryPostProcessors(beanFactory)

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); //Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime //(e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }

invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())

  • BeanDefinitionRegistryPostProcessor
    bean

    Bean

    @Componentpublic class MyBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException { RootBeanDefinition rootBeanDefinition = new RootBeanDefinition(); rootBeanDefinition.setBeanClass(MyTwoBean.class); beanDefinitionRegistry.registerBeanDefinition("myTwoBean",rootBeanDefinition); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException { }}
  • BeanFactoryPostProcessor
    bean

registerBeanPostProcessors(beanFactory)

invokeBeanFactoryPostProcessors(beanFactory)

BeanPostPocessor

initMessageSource()

initApplicationEventMulticaster()

// protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); } else { this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); } }

onRefresh()

Servlet web

//ServletWebServerApplicationContext # onRefresh() # 150protected void onRefresh() { super.onRefresh(); try { createWebServer(); } catch (Throwable ex) { throw new ApplicationContextException("Unable to start web server", ex); } }

super.onRefresh()
createWebServer()

// private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = getServletContext(); if (webServer == null && servletContext == null) { ServletWebServerFactory factory = getWebServerFactory(); this.webServer = factory.getWebServer(getSelfInitializer()); } else if (servletContext != null) { try { getSelfInitializer().onStartup(servletContext); } catch (ServletException ex) { throw new ApplicationContextException("Cannot initialize servlet context", ex); } } initPropertySources(); }

registerListeners()

protected void registerListeners() { //Register statically specified listeners first. // for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); } // listenerBean String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } //Publish early application events now that we finally have a multicaster... // Bean earlyApplicationEvents // Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }

finishBeanFactoryInitialization(beanFactory)

BeanFactory

Bean

finishRefresh()

protected void finishRefresh() { //Clear context-level resource caches (such as ASM metadata from scanning). // clearResourceCaches(); //Initialize lifecycle processor for this context. // ( ) initLifecycleProcessor(); //Propagate refresh to lifecycle processor first. // onRefresh() getLifecycleProcessor().onRefresh(); //Publish the final event. // publishEvent(new ContextRefreshedEvent(this)); //Participate in LiveBeansView MBean, if active. // LiveBeansView.registerApplicationContext(this);}

resetCommonCaches()

finally {}

protected void resetCommonCaches() { ReflectionUtils.clearCache(); AnnotationUtils.clearCache(); ResolvableType.clearCache(); CachedIntrospectionResults.clearClassLoader(getClassLoader()); }

refresh

refresh