SpringBoot-容器启动的时候执行一些内容

SpringBoot的ApplicationRunner、CommandLineRunner

场景:

在开发中可能会有这样的情景。需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunner和ApplicationRunner。他们的执行时机为容器启动完成的时候。

对比:

  • ApplicationRunner中run方法的参数为ApplicationArguments

  • CommandLineRunner接口中run方法的参数为String数组。
public class DemoApplication implements ApplicationRunner {

    public static void main(String[] args) {
        SpringApplication.run(ContextHierarchyDemoApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ApplicationContext fooContext = new AnnotationConfigApplicationContext(FooConfig.class);

    }
}

原文链接:https://blog.csdn.net/jdd92/article/details/81053404

猜你喜欢

转载自www.cnblogs.com/shix0909/p/12825523.html