springboot项目启动初始化方法常用的几种方式

描述

	在项目启动的过程中执行一些指定的业务逻辑代码,初始化数据,加载某一个配置文件等等,所有在项目启动过程中需要自动执行的业务。

场景

下面是我在开发过程中遇到的几个场景:

  1. 项目如果集成了其他的服务启动时需要同事启动服务,例如:Netty服务,ftp服务搭建,等等。
  2. 项目启动时需要进行初始化的配置,例如:初始化某一项信息或者对某一项信息预处理。
  3. 项目启动跟其他系统需要交互或者读取配置。

方式一:实现ApplicationRunner接口重写run方法逻辑

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class InitatialConfig implements ApplicationRunner {
    
    


    @Override
    public void run(ApplicationArguments args) throws Exception {
    
    
        System.out.println("项目启动初始化");
    }
}

在这里插入图片描述

方式二:实现CommandLineRunner 接口重写run方法逻辑

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class InitatialConfigCommand implements CommandLineRunner {
    
    



    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println("CommandLineRunner:"+"{}"+"接口实现方式重写");
    }
}

在这里插入图片描述

方式三:使用@PostConstruct注解的方式

    @PostConstruct
    public void testInitConfig(){
    
    

        System.out.println("@PostConstruct:"+"{}"+"注解方式实现启动初始化配置");
    }

在这里插入图片描述

初始化顺序

  1. @PostConstruct 注解方法
  2. CommandLineRunner接口实现
  3. ApplicationRunner接口实现

注意:

	当CommandLineRunner或者ApplicationRunner存在多个实现类的同时,可以使用@Order(1)注解进行顺序执行,该注解控制Bean的执行顺序。

猜你喜欢

转载自blog.csdn.net/A_awen/article/details/130647473