SpringBoot启动后,执行初始化方法

介绍

spring boot项目,有时我们希望在项目启动的时候,执行一些初始化方法,以下介绍几种实现方式

示例

1. CommandLineRunner

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println("我来自:CommandLineRunner");
    }
}

2. ApplicationRunner

@Component
public class MyApplicationRunner implements ApplicationRunner {
    
    
    @Override
    public void run(ApplicationArguments args) throws Exception {
    
    
        System.out.println("我来自:ApplicationRunner");
    }
}

3. PostConstruct

@Configuration
public class MyPostConstruct {
    
    
    @PostConstruct
    public void init() {
    
    
        System.out.println("我来自:PostConstruct");
    }
}

4. EventListener

@Configuration
public class MyEventListener {
    
    
    @EventListener
    public void init(ContextRefreshedEvent event) {
    
    
        System.out.println("我来自:EventListener");
    }
}
  • 码云 https://gitee.com/hweiyu/spring-boot-init-run.git

猜你喜欢

转载自blog.csdn.net/vbhfdghff/article/details/114031609