Spring Boot 啟動時,讓方法自動執(zhí)行的 4 種方法!
點擊關(guān)注公眾號,Java干貨及時送達(dá)
作者:FOEVERYANG
來源:www.cnblogs.com/lsgspace/p/10508180.html
在springBoot中我們有時候需要讓項目在啟動時提前加載相應(yīng)的數(shù)據(jù)或者執(zhí)行某個方法,那么實現(xiàn)提前加載的方式有哪些呢?
1、實現(xiàn)ServletContextAware接口并重寫其setServletContext方法
@Component
public class TestStarted implements ServletContextAware {
/**
* 在填充普通bean屬性之后但在初始化之前調(diào)用
* 類似于initializingbean的afterpropertiesset或自定義init方法的回調(diào)
*
*/
@Override
public void setServletContext(ServletContext servletContext) {
System.out.println("setServletContext方法");
}
}
注意:該方法會在填充完普通Bean的屬性,但是還沒有進(jìn)行Bean的初始化之前執(zhí)行。另外,關(guān)注公眾號Java技術(shù)棧,在后臺回復(fù):面試,可以獲取我整理的 Spring Boot 系列面試題和答案,非常齊全。
2、實現(xiàn)ServletContextListener接口
/**
* 在初始化Web應(yīng)用程序中的任何過濾器或servlet之前,將通知所有servletContextListener上下文初始化。
*/
@Override
public void contextInitialized(ServletContextEvent sce) {
//ServletContext servletContext = sce.getServletContext();
System.out.println("執(zhí)行contextInitialized方法");
}
3、將要執(zhí)行的方法所在的類交個spring容器掃描(@Component),并且在要執(zhí)行的方法上添加@PostConstruct注解或者靜態(tài)代碼塊執(zhí)行
@Component
public class Test2 {
//靜態(tài)代碼塊會在依賴注入后自動執(zhí)行,并優(yōu)先執(zhí)行
static{
System.out.println("---static--");
}
/**
* @Postcontruct’在依賴注入完成后自動調(diào)用
*/
@PostConstruct
public static void haha(){
System.out.println("@Postcontruct’在依賴注入完成后自動調(diào)用");
}
}
4、實現(xiàn)ApplicationRunner接口
/**
* 用于指示bean包含在SpringApplication中時應(yīng)運行的接口??梢远x多個applicationrunner bean
* 在同一應(yīng)用程序上下文中,可以使用有序接口或@order注釋對其進(jìn)行排序。
*/
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner的run方法");
}
5、實現(xiàn)CommandLineRunner接口
/**
* 用于指示bean包含在SpringApplication中時應(yīng)運行的接口??梢栽谕粦?yīng)用程序上下文中定義多個commandlinerunner bean,并且可以使用有序接口或@order注釋對其進(jìn)行排序。
* 如果需要訪問applicationArguments而不是原始字符串?dāng)?shù)組,請考慮使用applicationrunner。
*
*/
@Override
public void run(String... ) throws Exception {
System.out.println("CommandLineRunner的run方法");
}
最后,下面是 Spring Boot 系列教程:
https://github.com/javastacks/spring-boot-best-practice
學(xué)習(xí)了,你知道幾種?






關(guān)注Java技術(shù)??锤喔韶?/strong>

評論
圖片
表情

