Several common ways of springboot project startup initialization method

describe

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

Scenes

Here are a few scenarios I encountered during development:

  1. If the project integrates other services, colleagues need to start the service when starting, for example: Netty service, ftp service construction, and so on.
  2. Initial configuration is required when the project starts, for example: initializing a certain item of information or preprocessing a certain item of information.
  3. Project startup needs to interact or read configuration with other systems.

Method 1: Implement the ApplicationRunner interface to rewrite the logic of the run method

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("项目启动初始化");
    }
}

insert image description here

Method 2: Implement the CommandLineRunner interface to rewrite the logic of the run method

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:"+"{}"+"接口实现方式重写");
    }
}

insert image description here

Method 3: Using the @PostConstruct annotation

    @PostConstruct
    public void testInitConfig(){
    
    

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

insert image description here

initialization sequence

  1. @PostConstruct annotation method
  2. CommandLineRunner interface implementation
  3. Implementation of the ApplicationRunner interface

Notice:

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

Guess you like

Origin blog.csdn.net/A_awen/article/details/130647473