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 {

	}
}

還有一種方法也可以實現,就是使用@PostConstruct注解,詳見:https://www.jianshu.com/p/98cf7d8b9ec3

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM