At first, when the online search ran some programs at the start of the project, one way to implement Applicationlistener was to see that they did not copy their code directly, but instead wrote it manually. As follows:
package com.han.listener;import java.text.simpledateformat;import java.util.date;import org.springframework.context.applicationlistener;import Org.springframework.context.event.applicationcontextevent;import org.springframework.stereotype.component ; @Componentpublic class MyListener implements ApplicationListener< Applicationcontextevent> {public void onapplicationevent (applicationcontextevent event) {if (Event.getapplicationcontext () getParent () == null) {string contextname = event.getapplicationcontext (). GetDisplayName (); String time = new simpledateformat ("Yyyy-mm-dd hh:mm:ss"). Format (New Date ()); System.out.println (String.Format ("=================================web application event============ ==================== "+ " %s-->>%s-->>%s ", contextname, time, " Application event....\r\n "));}}}
However, after launch, it is found that there is a print start message, which seems to have achieved the expected results. But when my stop server stopped tomcat, I found that the console came out the same message, embarrassed ... After searching the web for custom listener why the server is stopped, it will try to change applicationcontextevent to contextrefreshedevent find that the message is no longer printed after the server has stopped. By literal means, applicationcontextevent listens to project container events (start, stop, etc.), while contextrefreshedevent literally is container refresh (start or initialize), According to its javadoc can also know meaning: Event raised when a ApplicationContext gets initialized or refreshed. In this record remind have the same puzzled friend, later pay attention to Javadoc reading.
The following are the correct usage codes for project startup execution:
package com.han.listener;import java.text.simpledateformat;import java.util.date;import org.springframework.context.applicationlistener;import org.springframework.context.event.contextrefreshedevent;import org.springframework.stereotype.component;@ Componentpublic class mylistener implements applicationlistener<contextrefreshedevent > {public void onapplicationevent (contextrefreshedevent event) {if ( Event.getapplicationcontext (). GetParent () == null) {String contextName = Event.getapplicationcontext (). GetDisplayName (); String time = new simpledateformat ("Yyyy-mm-dd hh:mm:ss"). Format (New Date ()); System.out.println (String.Format ("=================================web application event============ ==================== "+ " %s-->>%s-->>%s ", contextname, time, " Application event....\r\n "));}}}
This article is from the "11085961" blog, please be sure to keep this source http://11095961.blog.51cto.com/11085961/1930311
Considerations for implementing Applicationlistener to run certain programs when a project starts