Talking about the use of spring ApplicationListener listener

 Usage scenarios: In actual projects, we usually hope that after the web application starts successfully (here refers to the spring IOC container loading beans), initialization work, such as database loading, checking of specific tasks, etc. is performed.

 

 

 Implementation process : define a MyApplicationListener class and implement the ApplicationListener<ApplicationEvent> interface. If the configuration file (springmvc.xml, etc.) is used, this class is usually executed three times. To solve this problem, I define a variable isStart, and the default initial value is false.

code show as below:

@Controller
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
//Define this variable mainly to prevent the business code from being executed three times,
private static boolean isStart = false;
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (!isStart) {
// business code for a specific task
System.out.println("Initialization work here------");
isStart = true;
}
}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325353504&siteId=291194637