SpringBoot 程式啟動或退出時執行
阿新 • • 發佈:2021-01-18
技術標籤:JAVAspring bootspringjava
SpringBoot 程式啟動或退出時執行操作
啟動時
- 實現CommandLineRunner介面
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class CommandLineRunnerTest implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("這是測試CommandLineRunner的示例。");
}
}
- 實現ApplicationRunner介面
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class ApplicationRunnerTest implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println( "這是測試ApplicationRunner介面");
}
}
@Order註解:如果有多個實現類,而你需要他們按一定順序執行的話,可以在實現類上加上@Order註解。@Order(value=整數值)。SpringBoot會按照@Order中的value值從小到大依次執行。也就是先執行 1 再執行 2
@Component註解:把普通pojo例項化到spring容器中,泛指各種元件,就是說當我們的類不屬於各種歸類的時候(@Controller、@Services等的時候),我們就可以使用@Component來標註這個類。
結束時
- 實現DisposableBean介面
import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;
@Component
public class DisposableBeanTest implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("springboot程式結束 implements DisposableBean ");
}
}
- 通過@PreDistroy註解
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
@Component
public class ExitCode{
@PreDestroy
public void exit(){
System.out.println("springboot程式結束 執行@PreDestroy");
}
}
執行順序如下
先 @PreDestroy
後 DisposableBean
參考:https://blog.csdn.net/majinggogogo/article/details/103321281