SpringBoot提供了多种监听方式进行应用的启动停止监听,下面列举两种监听方式,便于在应用启动完成进行数据初始化或者在应用停止时进行垃圾回收,数据清理等等。
示例一
SpringBoot启动监听 ApplicationRunner
自定义ApplicationRunner 实现类,使用注解@Component把该实现类交于IOC管理。在SpringBoot启动成功后就会执行实现类的回调。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class ApplicationRunnerListener implements ApplicationRunner {
private static Logger logger = LoggerFactory.getLogger(ApplicationRunnerListener.class);
@Override
public void run(ApplicationArguments args) throws Exception {
logger.info("程序已运行");
}
}
示例二
SpringBoot启动监听 ApplicationListener
自定义ApplicationListener 实现类,使用注解@Component把该实现类交于IOC管理。在SpringBoot启动成功后就会执行实现类的回调。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class ApplicationReadyEventListener implements ApplicationListener<ApplicationReadyEvent> {
private static final Logger logger = LoggerFactory.getLogger(ApplicationReadyEventListener.class);
@Override
public void onApplicationEvent(ApplicationReadyEvent contextReadyEvent) {
logger.info("程序已启动");
}
}
示例三
SpringBoot停止监听 ApplicationListener
自定义ApplicationListener 实现类,使用注解@Component把该实现类交于IOC管理。在SpringBoot启动成功后就会执行实现类的回调。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
@Component
public class ApplicationClosedEventListener implements ApplicationListener<ContextClosedEvent> {
private static Logger logger = LoggerFactory.getLogger(ApplicationClosedEventListener.class);
@Override
public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
logger.info("程序已停止");
}
}