溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot關(guān)于容器啟動(dòng)事件總結(jié)

發(fā)布時(shí)間:2020-09-08 03:38:02 來(lái)源:腳本之家 閱讀:461 作者:yg_zhang 欄目:編程語(yǔ)言

在springboot 容器啟動(dòng)時(shí),我們需要在啟動(dòng)過(guò)程中做一些操作,比如啟動(dòng)容器后,執(zhí)行某些代碼。

spring 提供了監(jiān)聽(tīng)器,我們可以方便的實(shí)現(xiàn)這些操作。

在容器啟動(dòng)開(kāi)始時(shí):

package com.neo.filter;

import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationListener;

public class ApplicationStartingEventListener implements ApplicationListener<ApplicationStartingEvent> {
  @Override
  public void onApplicationEvent(ApplicationStartingEvent arg0) {
    System.err.println("ApplicationStartingEventListener");
  }

}

在容器啟動(dòng)完成后執(zhí)行操作:

package com.neo.filter;

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.Ordered;

public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartedEvent>,Ordered {

  @Override
  public void onApplicationEvent(ApplicationStartedEvent ev) {
    System.out.println("ApplicationStartedEventListener1");
  }
  @Override
  public int getOrder() {
    return 1;
  }

}

如果需要有順序執(zhí)行,我們可以實(shí)現(xiàn)Ordered接口,只越小,越先執(zhí)行。

package com;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.neo.filter.ApplicationStartedEventListener;
import com.neo.filter.ApplicationStartedEventListener2;
import com.neo.filter.ApplicationStartingEventListener;

@SpringBootApplication
public class DemoApplication {

  public static void main(String[] args) {
    SpringApplication app=new SpringApplication(DemoApplication.class);
    app.addListeners(new ApplicationStartedEventListener());
    app.addListeners(new ApplicationStartingEventListener());
    app.addListeners(new ApplicationStartedEventListener2());
    app.run(args);
  }
}

以上就是關(guān)于springboot容器啟動(dòng)事件的相關(guān)知識(shí)點(diǎn)以及實(shí)例代碼,感謝大家對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI