The business scenario

You need to initialize the DEVICE SDK after the program starts

plan

There are three ways to implement Spring Boot after it is started:

  • @PostConstruct
  • CommandLineRunner/ApplicationRunner
  • ContextRefreshedEvent

@PostConstruct

@postconstruct is executed after the constructor of its class executes

In this way, the class that initializes the method must be managed by Spring

@Component
public class SDKService {
    @PostConstruct
    public void init(a) {
        // Business logic...}}Copy the code

CommandLineRunner/ApplicationRunner

SpringBoot iterates through all entity classes implementing CommandLineRunner and executes the Run method after the project is started

Again, this class must be managed by Spring

If there is a sequencing problem, use the @order annotation to sort

@Component
public class SDKInitRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        // Business logic...}}Copy the code

ApplicationRunner is similar, except that the run method takes arguments of type ApplicationArguments

ContextRefreshedEvent

ContextRefreshedEvent is an application context refresh event

Is triggered when the Spring container is initialized and refreshed

Is this approach more suitable for caching?

@Component
public class SDKInitCache implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // Business logic...}}Copy the code

Note that in a Web project, this event fires twice, and I did not test it

conclusion

If it is initialized after launch, it is recommended to use CommandLineRunner/ApplicationRunner way