Spring項目啓動完成後,自動執行一次指定方法

SpringMVC

實現ApplicationListener接口,並實現 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法

@Service
public class SearchReceive implements  ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保證只執行一次
            //需要執行的方法
        }
    }
}

至於爲什麼先做判斷,因爲Spring存在兩個容器,一個是root application context ,另一個就是我們自己的 projectName-servlet context(作爲root application context的子容器)。這種情況下,就會造成onApplicationEvent方法被執行兩次。爲了避免上面提到的問題,我們可以只在root application context初始化完成後調用邏輯代碼,其他的容器的初始化完成,則不做任何處理。

SpringBoot

業務場景:
應用服務啓動時,加載一些數據和執行一些應用的初始化動作。如:刪除臨時文件,清除緩存信息,讀取配置文件信息,數據庫連接等。
SpringBoot提供了CommandLineRunner和ApplicationRunner接口。當接口有多個實現類時,提供了@order註解實現自定義執行順序,也可以實現Ordered接口來自定義順序。

注意:數字越小,優先級越高,也就是@Order(1)註解的類會在@Order(2)註解的類之前執行。

兩者的區別在於:
ApplicationRunner中run方法的參數爲ApplicationArguments,而CommandLineRunner接口中run方法的參數爲String數組。想要更詳細地獲命令行參數,那就使用ApplicationRunner接口

  • ApplicationRunner
@Component
@Order(value = 10)
public class AgentApplicationRun2 implements ApplicationRunner {
	@Override
	public void run(ApplicationArguments applicationArguments) throws Exception {

	}
}
  • CommandLineRunner
@Component
@Order(value = 11)
public class AgentApplicationRun implements CommandLineRunner {

	@Override
	public void run(String... strings) throws Exception {

	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章