每個SpringApplication将在JVM上注冊一個關閉鈎子,以確定ApplicationContext在退出時優雅地關閉。所有标準的Spring生命周期回調(例如
DisposableBean
接口,或者
@PreDestroy
注釋)都可以使用。
此外,bean還可以實作
org.springframework.boot.ExitCodeGenerator
SHI
并添加資源檔案application.properties:
name: JavaChen
Application啟動類
@SpringBootApplication
public class Springboot239Application implements CommandLineRunner {
@Autowired
private HelloWorldService helloWorldService;
public static void main(String[] args) {
SpringApplication.run(Springboot239Application.class, args);
}
@Override
public void run(String... args) {
System.out.println(this.helloWorldService.getMessage());
if (args.length > 0 && args[0].equals("exitcode")) {
throw new ExitException();
}
}
}
如果一些CommandLineRunner beans被定義必須以特定的次序調用,你可以額外實作
org.springframework.core.Ordered
接口或使用
@Order
注解。
利用command-line runner的這個特性,再配合依賴注入,可以在應用程式啟動時後首先引入一些依賴bean,例如data source、rpc服務或者其他子產品等等,這些對象的初始化可以放在run方法中。不過,需要注意的是,在run方法中執行初始化動作的時候一旦遇到任何異常,都會使得應用程式停止運作,是以最好利用try/catch語句處理可能遇到的異常。
每個SpringApplication在退出時為了確定ApplicationContext被優雅的關閉,将會注冊一個JVM的shutdown鈎子。所有标準的Spring生命周期回調(比如,DisposableBean接口或@PreDestroy注解)都能使用。
此外,如果beans想在應用結束時傳回一個特定的退出碼,可以實作
org.springframework.boot.ExitCodeGenerator
接口,例如上面例子中的ExitException異常類:
public class ExitException extends RuntimeException implements ExitCodeGenerator {
@Override
public int getExitCode() {
return 10;
}
}
@Component
public class HelloWorldService {
@Value("${name:World}")
private String name;
public String getMessage() {
return "Hello " + this.name;
https://github.com/csg103/springboot23-9}
}
源碼位址 https://github.com/csg103/springboot23-9