Exceptions related to Spring's refresh () method
If Spring is often used, especially those who have their own experiences in creating ApplicationContext objects, they must have seen such several exception messages:
1. LifecycleProcessor not initialized-call 'refresh' before invoking lifecycle methods via the context :......
2. BeanFactory not initialized or already closed-call 'refresh' before accessing beans via the ApplicationContext
3. ApplicationEventMulticaster not initialized-call 'refresh' before multicasting events via the context :......
The first message indicates that the LifecycleProcessor object is not initialized. You must call the 'refresh' method before calling the context life cycle method.
The second message indicates that the BeanFactory object has not been initialized or closed. You must call the 'refresh' method before using ApplicationContext to obtain the Bean.
The third message indicates that the ApplicationEventMulticaster object is not initialized and the 'refresh' method must be called before the context broadcast event.
These exception messages are related to the refresh method. What are the causes of these exceptions, why do we have to call the refresh method (defined in the AbstractApplicationContext class) in so many cases? before that, let's take a look at what the refresh method has done?
Public void refresh () throws BeansException, IllegalStateException {synchronized (this. startupShutdownMonitor) {// preparations before refreshing, including setting the start time, whether to activate the flag, initializing the property source to configure prepareRefresh (); // refresh BeanFactory by the subclass (create if not created), and return BeanFactory to describeanfactory = obtainFreshBeanFactory (); // prepare beanFactory for ApplicationContext to use prepareBeanFactory (BeanFactory ); try {// subclass postProcessBeanFactory (BeanFactory) can be modified using this method; // instantiate and call all registered BeanFactoryPostProcessor objects invokeBeanFactoryPostProcessors (beanFactory ); // instantiate and call all registered BeanPostProcessor objects registerBeanPostProcessors (beanFactory); // initialize MessageSourceinitMessageSource (); // initialize the event broadcaster initApplicationEventMulticaster (); // subclass override this method to do additional work in the refresh process onRefresh (); // register the application listener ApplicationListenerregisterListeners (); // instantiate all non-lazy-init beanfinisincluanfactoryinitialization (beanFactory ); // refresh completed, including initializing LifecycleProcessor, releasing refresh completed events, and other finishRefresh ();} catch (BeansException ex) {// Destroy already created singletons to avoid dangling resources. destroyBeans (); // Reset 'active' flag. cancelRefresh (ex); // Propagate exception to caller. throw ex ;}}}
Methods related to the three exception messages are: finishRefresh (), obtainFreshBeanFactory (), and initApplicationEventMulticaster ();
Protected void finishRefresh () {// initialize LifecycleProcessorinitLifecycleProcessor (); // Propagate refresh to lifecycle processor first. getLifecycleProcessor (). onRefresh (); // Publish the final event. publishEvent (new ContextRefreshedEvent (this); // participant in LiveBeansView MBean, if active. liveBeansView. registerApplicationContext (this );}
If the finishRefresh method is not called, The lifecycleProcessor member is null.
Protected export obtainFreshBeanFactory () {refreshBeanFactory (); // refresh BeanFactory. if beanFactory is null, create descriablelistablebeanfactory beanFactory = getBeanFactory (); if (logger. isDebugEnabled () {logger. debug ("Bean factory for" + getDisplayName () + ":" + beanFactory);} return beanFactory ;}
RefreshBeanFactory () is an abstract method that is truly implemented in the AbstractRefreshableApplicationContext class:
@ Overrideprotected final void refreshBeanFactory () throws BeansException {if (hasBeanFactory () {// if beanFactory is not null, destroy the Bean in beanFactory and disable destroyBeans (); closeBeanFactory ();} try {defalistlistablebeanfactory beanFactory = createBeanFactory (); // create beanFactorybeanFactory. setSerializationId (getId (); customizeBeanFactory (beanFactory); loadBeanDefinitions (beanFactory); synchronized (this. beanFactoryMonitor) {this. beanFactory = beanFactory; // assign values to beanFactory members} catch (IOException ex) {throw new ApplicationContextException ("I/O error parsing bean definition source for" + getDisplayName (), ex );}}
If the obtainFreshBeanFactory () method is not called, The beanFactory member is null.
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);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 + "]");}}}
All the three methods are called in the refresh () method. The above analysis shows that if the refresh method is not called, The lifecycleProcessor, beanFactory, and applicationEventMulticaster members in the context will be null. So far, we can analyze the reasons for these three exception messages in detail.
The following is a three-stage test code for the above three exception messages. The sequence is as follows:
1. public static void main(String[] args) {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();applicationContext.setConfigLocation("application-context.xml");applicationContext.start();applicationContext.close();}2. public static void main(String[] args) {ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();applicationContext.setConfigLocation("application-context.xml");applicationContext.getBean("xtayfjpk");applicationContext.close();}3. public static void main(String[] args) {GenericApplicationContext parent = new GenericApplicationContext();AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();context.setParent(parent);context.refresh();context.start();context.close();}
For the first exception message, the exception stack error occurs in applicationContext. start (); The following is the source code of the start () method:
public void start() {getLifecycleProcessor().start();publishEvent(new ContextStartedEvent(this));}
We can see that the lifecycleProcessor object needs to be obtained first in the start () method, but the refresh method is not called in the default constructor. Therefore, the lifecycleProcessor is null, so in getLifecycleProcessor () this exception message is thrown. The lifecycle method is defined in org. springframework. context. the start (), stop (), and isRunning () methods in the Lifecycle interface should be like this when creating the ClassPathXmlApplicationContext object if you are learning Spring at the beginning: classPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext ("application-context.xml"); so that the start () method is called directly without exception, why? This is because the ClassPathXmlApplicationContext (String configLocation) constructor finally calls:
Public ClassPathXmlApplicationContext (String [] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {super (parent); setConfigLocations (configLocations); if (refresh) {// The refresh value is true, in this way, the refresh method is automatically called to refresh ();}}
The second exception message indicates that an exception stack error occurs in applicationContext. getBean ("xforwarfjpk"), applicationContext. the getBean () method calls the getBean () method of beanFactory In the context. The code for obtaining the BeanFactory object is in the getBeanFactory () method of its base class ConfigurableListableBeanFactory:
@Overridepublic final ConfigurableListableBeanFactory getBeanFactory() {synchronized (this.beanFactoryMonitor) {if (this.beanFactory == null) {throw new IllegalStateException("BeanFactory not initialized or already closed - " +"call 'refresh' before accessing beans via the ApplicationContext");}return this.beanFactory;}}
BeanFactory is null because the default constructor of ClassPathXmlApplicationContext does not call the refresh () method. Therefore, an exception is thrown.
The third exception message indicates that an exception stack error occurs in context. refresh (). However, if the parent context is not set, context. setParent (parent) does not cause any exception in the sample code. This is because the finishRefresh () method in the refresh method calls the publishEvent method:
public void publishEvent(ApplicationEvent event) {Assert.notNull(event, "Event must not be null");if (logger.isTraceEnabled()) {logger.trace("Publishing event in " + getDisplayName() + ": " + event);}getApplicationEventMulticaster().multicastEvent(event);if (this.parent != null) {this.parent.publishEvent(event);}}
As shown above, if the parent context is not null, The pushlishEvent method of the parent container needs to be called, and the getApplicationEventMulticaster () method is called in this method to obtain an event broadcaster, the problem occurs here:
Private ApplicationEventMulticaster getApplicationEventMulticaster () throws IllegalStateException {if (this. applicationEventMulticaster = null) {// if it is null, throw the exception throw new IllegalStateException ("ApplicationEventMulticaster not initialized-" + "call 'refresh' before multicasting events via the context: "+ this);} return this. applicationEventMulticaster ;}
ApplicationEventMulticaster is instantiated in the initApplicationEventMulticaster method of the refresh method. If the parent context does not call the refresh method, the applicationEventMulticaster Member of the parent context is null, so an exception is thrown.
To sum up, there is only one root cause for these three exception messages, that is, when a context object is created, the refresh () method is not called. In Spring, ApplicationContext has many implementation classes. Some implementation classes automatically call the refresh () method during creation, while others do not. If not, manually call refresh () method. Generally, the implementation class that implements the WebApplicationContext interface and the refresh () method is not automatically used when the context object is created using the default constructor. Otherwise, the method is automatically called.