Spring -onRefresh() method

Hello, everyone. I’m Tian, a programmer.

The onRefresh() method of Spirng source code 6 is one of the refresh() methods, which appears to be an empty method but is very, very important for improving Spring extensibility.

As usual, post the source code for The refresh() method, the core method of Spring, so that readers can slip into the play.

@Override public void refresh() throws BeansException, An IllegalStateException {synchronized (enclosing startupShutdownMonitor) {/ / Prepare this context for refreshing. / / 1, the preparation for refresh prepareRefresh(); // The BeanFactory will be initialized, the BeanFactory will be loaded, and the internal bean will be registered ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Set the BeanFactory class loader and add a few beanPostProcessors. Manually register several special beans prepareBeanFactory(beanFactory); // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory);  // Invoke Factory processors registered as beans in the context. // Execute BeanFactory post-processor invokeBeanFactoryPostProcessors(beanFactory); / / 5, Register bean processors that intercept bean creation. / / registered bean registerBeanPostProcessors post processor (the beanFactory); // Initialize message source for this context. // initMessageSource(); // Initialize event multicaster for this context. initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. // // Listeners are listening to listeners beans and register them. // Instantiate all remaining (non-lazy-init) singletons. / / 8, complete the bean factory initialization method of * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * finishBeanFactoryInitialization (the beanFactory); // 3, select select (); } 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(); }}}Copy the code
OnRefresh () is a template method where specific subclasses can initialize special beans (before initializing Singleton Beans)Copy the code

That’s the main purpose of onRefresh(), so that’s the end of this article, thanks for reading!

Joking, only said that the role does not exemplify that and play hooligan there is no difference, next to Spirng’s typical implementation of Springboot for example.

This method is executed after Spring has loaded some special beans (built-in beans, classes that implement the bean factory postprocessor) and before instantiating the singleton bean. Let’s look at how Springboot calls this template method.

Clicking on the run() method, the core entry to Springboot, leads you to the onRefresh() method in Spring’s refresh() method, which is our hero today.

Click to see how Springboot’s onRresh() is implemented.

There are two package paths containing boot, must be the implementation method of Spirngboot.

This is an implementation of Spirng’s onRresh().

Comparing the onRresh() and SpirngbootRefersh implementation classes, Springboot has two more implementation classes, ReactiveWebServerApplicationContext classes and class ServletWebServerApplicationContext.

What do we do with the onRresh() method of each implementation?

The createWebServer() method is the same as the createWebServer() method.

What do the two createWebServer() methods do? We’ll debug it and take a look.

OnRresh ReactiveWebServerApplicationContext class () method to perform, isn’t see name knowledge meaning should be associated with webServer administration, limited to the space problem, leave a hole in a while.

ServletWebServerApplicationContext class onRefresh () method performs arrived, we went in.

private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = getServletContext(); If (webServer == null && servletContext == null) {if (webServer == null && servletContext == null) { GetWebServerFactory () = ServletWebServerFactory (); / / method / / or ServletWebServerApplicationContext this class created TomcatServletWebServerFactory class ServletWebServerFactory factory = getWebServerFactory(); // create Tomcat 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(); }Copy the code

The core should be factory.getWebServer(getSelfInitializer()), which creates a container. What kind of containers are there?

Let’s take a look at his implementation classes: Jetty, Mock, and Tomcat*. Tomcat doesn’t need to be mentioned.

What is the mock, with the attitude of learning baidu, did not understand, pass!

Let’s focus on Tomcat. In see TomcatServletWebServerFactory implementation class, the new object of a Tomcat, and made some Tomcat Settings, what protocol and port… And so on.

@Override public WebServer getWebServer(ServletContextInitializer... initializers) { if (this.disableMBeanRegistry) { Registry.disableRegistry(); } // create Tomcat Tomcat = new Tomcat(); File baseDir = (this.baseDirectory ! = null) ? this.baseDirectory : createTempDir("tomcat"); tomcat.setBaseDir(baseDir.getAbsolutePath()); // Sync non-blocking IO Connector Connector = new Connector(this.protocol); connector.setThrowOnFailure(true); tomcat.getService().addConnector(connector); customizeConnector(connector); tomcat.setConnector(connector); tomcat.getHost().setAutoDeploy(false); configureEngine(tomcat.getEngine()); for (Connector additionalConnector : this.additionalTomcatConnectors) { tomcat.getService().addConnector(additionalConnector); } prepareContext(tomcat.getHost(), initializers); // The TomcatWebServer instance is created and return getTomcatWebServer(tomcat); }Copy the code

The onRefresh() template method of Spirng is used in Springboot, and Tomcat is embedded in Springboot.

The onRefresh() method is a bit of a digression, but it gets a big loop in Springboot. However, a careful reading of Spirng and Springboot will help readers better understand the relationship.

It is also true to sigh the skill of Spirng authors and how strong the expansibility of Spirng is.

\