前言
在SpringBoot项目中,有一些操作(如初始化资源)需要在SpringBoot启动的时候,执行一次,还有如释放资源需要在SpringBoot关闭的时候运行。
实现
通过实现ApplicationListener来实现监听启动和关闭,达到启动和关系的时候,运行代码:
新建MyApplicationStartup
@Component public class MyApplicationStartup implements ApplicationListener<ApplicationReadyEvent> { private static final Log log = LogFactory.getLog(MyApplicationStartup.class); /** * 运行到这里,说明程序已经启动起来了 */ @Override public void onApplicationEvent(final ApplicationReadyEvent event) { // 这里写上自定义需要初始化的一些代码了 } }
新建MyApplicationShutdown
@Component public class MyApplicationShutdown implements ApplicationListener<ContextClosedEvent> { private static final Log log = LogFactory.getLog(MyApplicationShutdown.class); @Override public void onApplicationEvent(ContextClosedEvent contextClosedEvent) { log.error("myapplication shutdown"); // 这里放系统关闭时候,需要释放资源等的代码 } }
文章评论
buy cialis usa Viagra Bestellen Aus Osterreich Dlsuoy Levitra How To Take Gvrxpq buy cheap generic cialis uk hypocalcemia Fmbjcq - purchase cialis online Venta Kamagra En Linea