java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot项目启动后及关闭前执行指定代码

SpringBoot项目启动后及关闭前执行指定代码实现方式

作者:0和1搭建网络世界

文章介绍了在Spring Boot项目中,如何通过注解@Component、@PostConstruct和@PreDestroy以及实现ApplicationRunner和CommandLineRunner接口来订阅和取消订阅消息,每种方法都有其特点和适用场景

应用场景

当项目中需要订阅消息时,启动项目后,需开始订阅,而在项目关闭前则需要取消订阅。

具体实现

方法一:通过使用注解

@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方法的入参类型不一致

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文