每个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