Designed by 77
加载资源 ......
感谢 ♥ 作者
先不感谢了

SpringBoot应用在服务启动后进行一些初始化工作

在一些场景中,当SpringBoot项目启动后,我们可能会需要做一些写入缓存或者初始常量信息等的初始化工作,此时便需要使用SpringBoot提供的Runner来实现。

SpringBoot实际上给我们提供了两种在应用启动后立即执行某些方法的方式,它们分别是【ApplicationRunner】和CommandLineRunner】。两者的相同的在于它们都是在SpringApplication执行之后开始执行的,而不同点则在于CommandLineRunner接口提供的方法只能传递字符串,而ApplicationRunner是使用ApplicationArguments用来接收参数的,因此这个方式可以在更加复杂的场景中使用。

通过实现CommandLineRunner接口来实现启动后执行特定逻辑

@Component
public class InitRunner implements CommandLineRunner {
    /**
     * 在服务启动完成(特指SpringApplication)后立即执行
     */
    @Override
    public void run(String... args) throws Exception {
        System.out.println("This will be executed when the project is started!");
    }
}

 通过实现ApplicationRunner接口来实现启动后执行特定逻辑

@Component
public class InitRunner implements ApplicationRunner {
    /**
     * 在服务启动完成(特指SpringApplication)后立即执行
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
       System.out.println("This will be executed when the project is started!");
    }
}

这两种方式的实现都很简单,直接实现了相应的接口就可以了,但别忘了要在类上加上@Component注解。

注册多个实现并指定初始化工作的优先级

如果想要将多个初始化工作拆分开的话,只要生成多个实现类即可。

另外如果想要指定启动方法执行的顺序的话,则可以通过实现【org.springframework.core.Ordered】接口或者使用【org.springframework.core.annotation.Order】注解来实现目的。

@Component
@Order(value = 1) 
public class InitRunner1 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {       
        System.out.println("i like yanggb!");
    }    
}
@Component
@Order(value = 2) 
public class InitRunner2 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {       
        System.out.println("i like yanggb too!");
    }    
}

在@Order注解中指定的value值越小,则执行的优先级越高,比如在上面的代码中就会先打印出【i like yanggb!】,然后再打印出【i like yanggb too!】。

 

"所有不合时宜的相遇都是遗憾。"

posted @ 2020-12-28 08:15  yanggb  阅读(847)  评论(0编辑  收藏  举报