起初在网上搜索在项目启动时运行某些程序时,看到其中有用实现ApplicationListener来做的一种方法,当时没有直接复制他们的代码,而是手动写的。如下:
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;
@Component
public 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"));
}
}
}
但是启动后发现确实有打印启动信息,似乎达到了预想中的结果。但是当我stop server停止tomcat时却发现控制台又出来同样的消息,尴尬......后在网上搜索自定义的listener为何在服务器停止时也会执行未果,便试着把ApplicationContextEvent换成ContextRefreshedEvent 发现在服务器停止后不再打印消息。通过字面意思发现,ApplicationContextEvent监听的是项目容器事件(启动、停止等),而ContextRefreshedEvent 字面理解即是容器刷新(启动或说初始化),根据其javadoc也可以知道意思:Event raised when an ApplicationContext
gets initialized or refreshed.。在此记录提醒有同样疑惑的朋友,以后注重javadoc的阅读。
以下是做项目启动执行的正确使用代码:
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;
@Component
public 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"));
}
}
}
转载于:https://blog.51cto.com/11095961/1930311