我意识到以编程方式退出SpringBoot 4应用程序我想调用SpringApplication的exit()方法,但是如何获取对它的引用?
当然我可以在main()方法中访问它,但我问,因为如果我在某个类中加载资源并且失败,我想终止应用程序,但是从那个类我可以'弄清楚如何访问SpringApplication。
...谢谢
答案 0 :(得分:1)
此用例的更简洁方法是使用事件&侦听器,其中您必须将侦听器添加到SpringApplication类,该类将侦听事件,例如在您的情况下资源加载失败,然后相应地执行操作,即退出应用程序。您可以通过实现ApplicationContextAware接口来获取应用程序上下文句柄。关于活动和细节的详细信息可以找到监听器here。
MyEvent类: -
public class MyEvent extends ContextRefreshedEvent {
private static final long serialVersionUID = 1L;
@Autowired
public MyEvent(ApplicationContext source) {
super(source);
}
}
MyEvent监听器类: -
@Component
public class MyListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event instanceof MyEvent){
SpringApplication.exit(event.getApplicationContext(), new ExitCodeGenerator() {
@Override
public int getExitCode() {
return 2;
}
});
}
}
}
资源加载器类: -
@Component
public class MyResourceLoader implements ApplicationContextAware, CommandLineRunner {
private ApplicationContext ctx ;
@Autowired
private ApplicationEventPublisher publisher;
@Override
public void run(String... args) throws Exception {
//inside RUN for resource load failure
publisher.publishEvent(new MyEvent(ctx));
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
ctx = applicationContext;
}
}