SpringBoot项目启动时初始化操作方式

1.实现InitializingBean重写afterPropertiesSet()方法。

@Component
@Slf4j
public class InitOneTest implements InitializingBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("InitOneTest init success");
    }
}

2.注解@PostConstruct

在类构造方法之后执行

@Component
@Slf4j
public class InitTwoTest {
    @PostConstruct
    public void init(){
      log.info("InitTwoTest init success");
    }
}

3.实现CommandLineRunner,重写run()方法

@Component
@Slf4j
@Order(1)// 启动顺序
public class InitThreeTest implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        log.info("InitThreeTest initial success");
    }
}

4.实现ApplicationRunner,重写run()方法

@Component
@Slf4j
@Order(2)// 启动顺序
public class InitFourTest implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("InitFourTest init success");
    }
}

5.实现监听器ApplicationListener

注意点:这种方式在springmvc-spring的项目中使用的时候会出现执行两次的情况。这种是因为在加载spring和springmvc的时候会创建两个容器,都会触发这个事件的执行。这时候只需要在onApplicationEvent方法中判断是否有父容器即可

@Component
@Slf4j
public class InitFiveTest implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if(event.getApplicationContext().getParent() == null){
            log.info("InitFiveTest init success");
        }
    }
}

启动顺序截图:

image

posted @ 2023-04-01 15:17  土木转行的人才  阅读(147)  评论(0编辑  收藏  举报