应用场景
当项目中需要订阅消息时,启动项目后,需开始订阅,而在项目关闭前则需要取消订阅。
具体实现
方法一:通过使用注解@Component、@PostConstruct和@PreDestroy形式完成。
因为上面三个注解是springboot自带,所以不需要额外添加依赖。代码如下
@SpringBootApplication
@EnableAutoConfiguration
public class springMVCProjectApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(springMVCProjectApplication.class, args);
context.close();
}
}
@Component
@Slf4j
public class RunScript {
@PostConstruct
public void start(){
log.info("启动后执行");
}
@PreDestroy
public void end(){
log.info("关闭前执行");
}
}

从日志可以看出,启动后执行了start方法,而关闭前执行了end方法。
方法二:通过实现ApplicationRunner接口
启动类的代码复用方法一中
@Component
@Slf4j
public class RunScript implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("在程序启动后执行:"+args);
}
@PreDestroy
public void destory(){
log.info("在程序关闭后执行");
}
}

通过上面日志也可以看出,同样实现的目的,通过重写ApplicationRunner接口的run方法,可以传入参。
方法三:通过实现CommandLineRunner接口
启动类的代码复用方法一中
@Component
@Slf4j
public class RunScript implements CommandLineRunner{
@PreDestroy
public void destory(){
log.info("在程序关闭后执行");
}
@Override
public void run(String... args) throws Exception {
log.info("在程序启动后执行:"+args);
}
}

通过日志可以看到,和方法二基本一致,但是重写的run方法的入参类型不一致
原文链接:https://blog.csdn.net/study_study_know/article/details/111400695