如果你想在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注解

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐