In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use refresh, the core method of spring-connet". In daily operation, I believe many people have doubts about how to use refresh, the core method of spring-connet. The editor has consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use refresh, the core method of spring-connet." Next, please follow the editor to study!
Preface
Refresh is the core method of ApplicationContext, if you take care of this method, ApplicationContext is done.
Public void refresh () throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {prepareRefresh (); ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory (); prepareBeanFactory (beanFactory); try {postProcessBeanFactory (beanFactory) InvokeBeanFactoryPostProcessors (beanFactory); registerBeanPostProcessors (beanFactory); initMessageSource (); initApplicationEventMulticaster () OnRefresh (); registerListeners (); finishBeanFactoryInitialization (beanFactory) FinishRefresh () } catch (BeansException ex) {if (logger.isWarnEnabled ()) {logger.warn ("Exception encountered during context initialization -" + "cancelling refresh attempt:" + ex) } destroyBeans (); cancelRefresh (ex); throw ex;} finally {resetCommonCaches () } prepareRefresh
Declare and implement in the AbstractApplicationContext class
Protected void prepareRefresh () {/ / Startup time this.startupDate = System.currentTimeMillis (); / / whether to go out and close the status this.closed.set (false); / / whether it is active or not, this state is very important this.active.set (true) If (logger.isInfoEnabled ()) {logger.info ("Refreshing" + this);} initPropertySources (); / / check configuration getEnvironment (). ValidateRequiredProperties (); / / early event this.earlyApplicationEvents = new LinkedHashSet ();}
InitPropertySources
InitPropertySources states that in AbstractApplicationContext, which is rewritten by AbstractRefreshableWebApplicationContext and GenericWebApplicationContext respectively, you can simply add web's servletContext and servletConfig to the configuration.
Protected void initPropertySources () {/ / For subclasses: do nothing by default.}
GenericWebApplicationContext
Protected void initPropertySources () {ConfigurableEnvironment env = getEnvironment (); if (env instanceof ConfigurableWebEnvironment) {((ConfigurableWebEnvironment) env) .initPropertySources (this.servletContext, null);}}
AbstractRefreshableWebApplicationContext
Protected void initPropertySources () {ConfigurableEnvironment env = getEnvironment (); if (env instanceof ConfigurableWebEnvironment) {((ConfigurableWebEnvironment) env) .initPropertySources (this.servletContext, this.servletConfig);}}
ObtainFreshBeanFactory
Protected ConfigurableListableBeanFactory obtainFreshBeanFactory () {refreshBeanFactory (); ConfigurableListableBeanFactory beanFactory = getBeanFactory (); if (logger.isDebugEnabled ()) {logger.debug ("Bean factory for" + getDisplayName () + ":" + beanFactory);} return beanFactory;}
RefreshBeanFactory
Protected final void refreshBeanFactory () throws BeansException {if (hasBeanFactory ()) {/ / since you want to refresh, you must fail all bean destroyBeans (); / / close the factory closeBeanFactory () } try {/ / create bean. Students who have read the BeanFactory series of articles should know that they will create that object, DefaultListableBeanFactory beanFactory = createBeanFactory (); beanFactory.setSerializationId (getId ()) / / for the content of customizeBeanFactory, please see the BeanFactory series chapter customizeBeanFactory (beanFactory); loadBeanDefinitions (beanFactory); synchronized (this.beanFactoryMonitor) {this.beanFactory = beanFactory }} catch (IOException ex) {throw new ApplicationContextException ("I error parsing bean definition source for O error parsing bean definition source for" + getDisplayName (), ex);}}
LoadBeanDefinitions
Create AnnotatedBeanDefinitionReader and ClassPathBeanDefinitionScanner and load the corresponding class and basePackages. Note that if you do not call the method of ApplicationContext, there is no class and basePackages. Spring default scan path is not here
Protected void loadBeanDefinitions (DefaultListableBeanFactory beanFactory) {AnnotatedBeanDefinitionReader reader = getAnnotatedBeanDefinitionReader (beanFactory); ClassPathBeanDefinitionScanner scanner = getClassPathBeanDefinitionScanner (beanFactory); BeanNameGenerator beanNameGenerator = getBeanNameGenerator (); if (beanNameGenerator! = null) {reader.setBeanNameGenerator (beanNameGenerator); scanner.setBeanNameGenerator (beanNameGenerator) BeanFactory.registerSingleton (AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR, beanNameGenerator);} ScopeMetadataResolver scopeMetadataResolver = getScopeMetadataResolver (); if (scopeMetadataResolver! = null) {reader.setScopeMetadataResolver (scopeMetadataResolver); scanner.setScopeMetadataResolver (scopeMetadataResolver) } if (! this.annotatedClasses.isEmpty ()) {if (logger.isInfoEnabled ()) {logger.info ("Registering annotated classes: [" + StringUtils.collectionToCommaDelimitedString (this.annotatedClasses) + "]") } reader.register (ClassUtils.toClassArray (this.annotatedClasses)) } if (! this.basePackages.isEmpty ()) {if (logger.isInfoEnabled ()) {logger.info ("Scanning base packages: [" + StringUtils.collectionToCommaDelimitedString (this.basePackages) + "]") } scanner.scan (StringUtils.toStringArray (this.basePackages));} String [] configLocations = getConfigLocations () If (configLocations! = null) {for (String configLocation: configLocations) {try {Class clazz = getClassLoader () .loadClass (configLocation) If (logger.isInfoEnabled ()) {logger.info ("Successfully resolved class for [" + configLocation + "]");} reader.register (clazz) } catch (ClassNotFoundException ex) {if (logger.isDebugEnabled ()) {logger.debug ("Could not load class for config location [" + configLocation +) "]-trying package scan. "+ ex);} int count = scanner.scan (configLocation) If (logger.isInfoEnabled ()) {if (count = = 0) {logger.info ("No annotated classes found for specified class/package [" + configLocation + "]") } else {logger.info ("Found" + count + "annotated classes in package [" + configLocation + "]") }} prepareBeanFactory
Add some bean or some rules to BeanFactory
* / protected void prepareBeanFactory (ConfigurableListableBeanFactory beanFactory) {/ / Tell the internal bean factory to use the context's class loader etc. BeanFactory.setBeanClassLoader (getClassLoader ()); beanFactory.setBeanExpressionResolver (new StandardBeanExpressionResolver (beanFactory.getBeanClassLoader (); beanFactory.addPropertyEditorRegistrar (new ResourceEditorRegistrar (this, getEnvironment (); / / Configure the bean factory with context callbacks. BeanFactory.addBeanPostProcessor (new ApplicationContextAwareProcessor (this)); / / the following is to ignore dependencies, automatically ignoring the dependencies of the following objects, 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. / / MessageSource registered (and found for autowiring) as a 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. BeanFactory.addBeanPostProcessor (new ApplicationListenerDetector (this)); / / Detect a LoadTimeWeaver and prepare for weaving, if found. If (beanFactory.containsBean (LOAD_TIME_WEAVER_BEAN_NAME)) {beanFactory.addBeanPostProcessor (new LoadTimeWeaverAwareProcessor (beanFactory)); / / Set a temporary ClassLoader for type matching. BeanFactory.setTempClassLoader (new ContextTypeMatchClassLoader (beanFactory.getBeanClassLoader ();} / / Register default environment beans. 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 ());}} postProcessBeanFactory
This is the method that the subclass AnnotationConfigReactiveWebServerApplicationContext overrides the parent class, so the postProcessBeanFactory function is designed to provide its own behavior for the subclass. Its function is exactly the same as prepareBeanFactory. It's just that we're dealing with a different person.
Protected void postProcessBeanFactory (ConfigurableListableBeanFactory beanFactory) {beanFactory.addBeanPostProcessor (new ServletContextAwareProcessor (this.servletContext, this.servletConfig)); beanFactory.ignoreDependencyInterface (ServletContextAware.class); beanFactory.ignoreDependencyInterface (ServletConfigAware.class); WebApplicationContextUtils.registerWebApplicationScopes (beanFactory, this.servletContext); WebApplicationContextUtils.registerEnvironmentBeans (beanFactory, this.servletContext, this.servletConfig) } invokeBeanFactoryPostProcessors 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 ();}} registerBeanPostProcessors
Get the implementation class of BeanPostProcessors and subinterface from BeanFactory. Sort it and then add it to the BeanPostProcessor collection of beanFactory for subsequent operations on the aspect. The function can be performed in the above method to ensure singleness, the execution is repeated.
Protected void registerBeanPostProcessors (ConfigurableListableBeanFactory beanFactory) {PostProcessorRegistrationDelegate.registerBeanPostProcessors (beanFactory, this);} initMessageSourceprotected void initMessageSource () {ConfigurableListableBeanFactory beanFactory = getBeanFactory (); if (beanFactory.containsLocalBean (MESSAGE_SOURCE_BEAN_NAME)) {this.messageSource = beanFactory.getBean (MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); / / Make MessageSource aware of parent MessageSource. If (this.parent! = null & & this.messageSource instanceof HierarchicalMessageSource) {HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource () = = null) {/ / Only set parent context as parent MessageSource if no parent MessageSource / / registered already. Hms.setParentMessageSource (getInternalParentMessageSource ());}} if (logger.isDebugEnabled ()) {logger.debug ("Using MessageSource [" + this.messageSource + "]") }} else {/ / Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource (); dms.setParentMessageSource (getInternalParentMessageSource ()); this.messageSource = dms; beanFactory.registerSingleton (MESSAGE_SOURCE_BEAN_NAME, this.messageSource) If (logger.isDebugEnabled ()) {logger.debug ("Unable to locate MessageSource with name'" + MESSAGE_SOURCE_BEAN_NAME + "': using default [" + this.messageSource + "]") } initApplicationEventMulticasterprotected void initApplicationEventMulticaster () {ConfigurableListableBeanFactory beanFactory = getBeanFactory (); if (beanFactory.containsLocalBean (APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {this.applicationEventMulticaster = beanFactory.getBean (APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class) If (logger.isDebugEnabled ()) {logger.debug ("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");}} else {this.applicationEventMulticaster = new SimpleApplicationEventMulticaster (beanFactory) BeanFactory.registerSingleton (APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster) If (logger.isDebugEnabled ()) {logger.debug ("Unable to locate ApplicationEventMulticaster with name'" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "': using default [" + this.applicationEventMulticaster + "]") } onRefresh protected void onRefresh () {this.themeSource = UiApplicationContextUtils.initThemeSource (this);} registerListeners protected void registerListeners () {/ / Register statically specified listeners first. For (ApplicationListener listener: getApplicationListeners ()) {getApplicationEventMulticaster () .addApplicationListener (listener);} / / Do not initialize FactoryBeans here: We need to leave all regular beans / / uninitialized to let post-processors apply to them! 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... Set earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess! = null) {for (ApplicationEvent earlyEvent: earlyEventsToProcess) {getApplicationEventMulticaster () .multicastEvent (earlyEvent);} finishBeanFactoryInitialization
Finish beanfactory. Because of different functions of containers, after successful startup, multiple factory are required to perform different operations.
Protected void finishBeanFactoryInitialization (ConfigurableListableBeanFactory beanFactory) {/ / if a conversion service exists Obtained from the beanFactory factory and set to beanFctory if (beanFactory.containsBean (CONVERSION_SERVICE_BEAN_NAME) & & beanFactory.isTypeMatch (CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {beanFactory.setConversionService (beanFactory.getBean (CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) } if (! beanFactory.hasEmbeddedValueResolver ()) {beanFactory.addEmbeddedValueResolver (new StringValueResolver ()) {@ Override public String resolveStringValue (String strVal) {return getEnvironment () .resolvePlaceholders (strVal) }});} / a comparative function String [] weaverAwareNames = beanFactory.getBeanNamesForType (LoadTimeWeaverAware.class, false, false); for (String weaverAwareName: weaverAwareNames) {getBean (weaverAwareName) } / / Stop using the temporary ClassLoader for type matching. BeanFactory.setTempClassLoader (null); / / Allow for caching all bean definition metadata, not expecting further changes. BeanFactory.freezeConfiguration (); / / Instantiate all remaining (non-lazy-init) singletons. BeanFactory.preInstantiateSingletons ();} finishRefresh
Successful processing of refresh
Protected void finishRefresh () {/ / initialize ApplicationContext lifecycle initLifecycleProcessor (); / execute lifecycle onRefresh getLifecycleProcessor (). OnRefresh (); / / execute CntextRefreshed event publishEvent (new ContextRefreshedEvent (this)); / / Participate in LiveBeansView MBean, if active. LiveBeansView.registerApplicationContext (this);} Summary
PrepareRefresh asked ApplicationContext to make some preparations.
ObtainFreshBeanFactory subclasses resolve what BeanFactory to use, and let some subclasses handle BeanFactory on their own
PrepareBeanFactory is a unified behavior of AbstractApplicationContext specification BeanFactory.
InvokeBeanFactoryPostProcessors executes BeanPostProcessors
RegisterBeanPostProcessors sorts the BeanPostProcessors and adds beanFactory. The next step is to initialize and execute the ApplicationContext behavior
InitMessageSource initializes MessageSource
InitApplicationEventMulticaster initializes ApplicationEventMulticaster
OnRefresh is useless
RegisterListeners execution event
FinishBeanFactoryInitialization collates beanFactory.
FinishRefresh
At this point, the study on "how to use refresh, the core method of spring-connet", is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.