Spring Boot启动的时候运行一些特定的代码
注意事项:不管是实现接口还是使用注解来实现功能,他们的类上都需要添加@Component注解。第一种:创建类,并实现ApplicationRunner接口,重写run方法。第二种:创建类,实现CommandLineRunner接口,重写run方法。第三种:注解式,创建方法,添加注解:@PostConstruct。如果你想在Spring Boot启动的时候运行一些特定的代码。
·
如果你想在Spring Boot启动的时候运行一些特定的代码
共有三种方式可以实现该功能:
第一种:创建类,并实现ApplicationRunner接口,重写run方法
@Component public class InitStart implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { //此处为项目启动后执行的方法 } }
第二种:创建类,实现CommandLineRunner接口,重写run方法
@Component public class InitStart implements CommandLineRunner { @Override public void run(String... args) throws Exception { //此处为项目启动后执行的方法 } }
第三种:注解式,创建方法,添加注解:@PostConstruct
@Component public class InitStart implements CommandLineRunner { @PostConstruct public void init(){ //此处为项目启动后执行的方法 } }
注意事项:不管是实现接口还是使用注解来实现功能,他们的类上都需要添加@Component注解
更多推荐
已为社区贡献4条内容
所有评论(0)