When the app starts, it usually wants to preload some resources at this time, globally.
Spring will use Applicationeventpublisher to trigger related applicationcontextevent when the application context is manipulated, and we can listen to these events to do something.
There are several applicationcontextevent in spring:
The timing of the execution of Contextrefreshedevent is:
1 Event raised when an {@code ApplicationContext} gets initialized or refreshed.
We usually refresh our preloaded resources when spring loads or refreshes the application context, and we can do this by listening to contextrefreshedevent.
The code is as follows:
1 @Component2 Public classSpringhandlersproviderImplementsApplicationlistener<contextrefreshedevent> {3Lists<xxx> handlerlist =lists.newhashlist ();4 @Override5 Public voidonapplicationevent (Contextrefreshedevent event) {6 //Do something7 handlerlist.add (XXX);8 }9}
But for the Tomcat project, we typically load two context containers a parent container, an MVC sub-container
- Parent container {@code contextrefreshedevent[source=root webapplicationcontext:startup date [Thu Sep 14:52:08 CST]; Root of CO ntext Hierarchy]}
- MVC container {@code contextrefreshedevent[source=webapplicationcontext for namespace ' Springmvc-servlet ': startup Date [Thu Sep 14:52:34 CST 2016]; Parent:root Webapplicationcontext]}
This triggers two contextrefreshedevent events, causing the logic to listen for this event to be executed two times.
Avoidance methods:
1: Executes only once when the parent container is loaded
1 @Component2 Public classSpringhandlersproviderImplementsApplicationlistener<contextrefreshedevent> {3Lists<xxx> handlerlist =lists.newhashlist ();4 @Override5 Public voidonapplicationevent (Contextrefreshedevent event) {6 if(Predicates.isnull (). Apply (Event.getapplicationcontext (). GetParent ())) {7 //Do something8 handlerlist.add (XXX);9 }Ten } One}
2: Empty the container where the resource is stored each time the Onapplicationevent () method is executed
1 @Component2 Public classSpringhandlersproviderImplementsApplicationlistener<contextrefreshedevent> {3Lists<xxx> handlerlist =lists.newhashlist ();4 @Override5 Public voidonapplicationevent (Contextrefreshedevent event) {6 handlerlist.clear ();7 8 //Do something9 handlerlist.add (XXX);Ten } One}
About the Contextrefreshedevent event in the Spring Javaweb project