2021-03-14-SpringBoot project executes other code when it starts

Preface

  • Many times we need to execute some other code at the same time as the project starts
  • Let's talk about how some SpringBoot projects are implemented

method one

  • Implement ApplicationRunner interface
@Component
public class RunUtilTest  implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(1111);

    }
}

Way two

  • Implement the CommandLineRunner interface
  • The difference between the two interfaces is that the incoming parameters are different, but we generally don’t need to use the incoming parameters, so these two methods actually have the same effect.
@Component
public class RunUtilTest2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(2133254);
    }
}

@Order annotation

  • Added to the class, the smaller the value of the annotation, the earlier it will be executed
  • For example, the following code is RunUtilTest2 executed first
@Component
@Order(value=1)
public class RunUtilTest2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(2133254);
    }
}




@Component
@Order(value=2)
public class RunUtilTest  implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(1111);

    }
}

Guess you like

Origin blog.csdn.net/qq_41270550/article/details/113983372