監聽器
- spring框架的啟動入口 ContextLoaderListener
- 作用:在啟動Web 容器時,自動裝配Spring applicationContext.xml 的配置信息。
因為它實現了ServletContextListener 這個接口,在web.xml 配置這個監聽器,啟動容器時,就會默認執行它實現的方法。在ContextLoaderListener 中關聯了ContextLoader 這個類,所以整個加載配置過程由ContextLoader 來完成。
借用監聽器來作為Spring項目啟東時來初始化數據
Spring的事件驅動模型由三部分組成
- 事件: ApplicationEvent,繼承自JDK的EventObject,所有事件都要繼承它,也就是被觀察者
- 事件發布者: ApplicationEventPublisher及ApplicationEventMulticaster接口,使用這個接口,就可以發布事件了
- 事件監聽者: ApplicationListener,繼承JDK的EventListener,所有監聽者都繼承它,也就是我們所說的觀察者,當然我們也可以使用注解 @EventListener,效果是一樣的
事件
在Spring框架中,默認對ApplicationEvent事件提供了如下支持:
- ContextStartedEvent:ApplicationContext啟動后觸發的事件
- ContextStoppedEvent:ApplicationContext停止后觸發的事件
- ContextRefreshedEvent:ApplicationContext初始化或刷新完成后觸發的事件;(容器初始化完成后調用,所以我們可以利用這個事件做一些初始化操作)
- ContextClosedEvent:ApplicationContext關閉后觸發的事件;(如web容器關閉時自動會觸發spring容器的關閉,如果是普通java應用,需要調用ctx.registerShutdownHook();注冊虛擬機關閉時的鈎子才行)
event事件
public class TestEvent extends ApplicationEvent { private String message; public TestEvent(Object source) { super(source); } public void getMessage() { System.out.println(message); } public void setMessage(String message) { this.message = message; } }
事件監聽者
@Component public class ApplicationListenerTest implements ApplicationListener<TestEvent> { @Override public void onApplicationEvent(TestEvent testEvent) { testEvent.getMessage(); } }
事件發布
@RunWith(SpringRunner.class) @SpringBootTest public class EventTest { @Autowired private ApplicationContext applicationContext; @Test public void publishTest() { TestEvent testEvent = new TestEvent(""); testEvent.setMessage("hello world"); applicationContext.publishEvent(testEvent); } }
輸出helloworld
參考:https://blog.csdn.net/pjmike233/article/details/81908540
關於Spring中過濾器,攔截器,監聽器的使用及理解:
參考:https://blog.csdn.net/c_royi/article/details/82687724
定時器
普通計時器:通過Timer類對象和TimeTask類來實現
import java.util.Timer; import java.util.TimerTask; public class TimerDemo { public static void main(String[] args) { timerTest(); } public static void timerTest(){ //創建一個定時器 Timer timer = new Timer(); //schedule方法是執行時間定時任務的方法 timer.schedule(new TimerTask() { //run方法就是具體需要定時執行的任務 @Override public void run() { System.out.println("timer測試!!!"); } }, 1000, 10000); } }
可以借助ApplicationListener作為定時器實現每天00:00執行任務的代碼
@Component public class SystemInitListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { //創建定時器 Timer timer = new Timer(); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE,1); calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DATE),0,0,0); long timeInterval = 24 * 60 * 60 * 1000; timer.schedule(new TimerTask() { @Override public void run() { // 每天00:00需要做的事情 } }, calendar.getTime(), timeInterval);
}
}