SpringBoot项目启动时指定service的指定方法

落日映苍穹つ 2023-06-24 08:12 20阅读 0赞

springboot在项目启动时候给我们提供了两种“开机启动”某些方法的功能

  • ApplicationRunner
  • CommandLineRunner

这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的。

CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的,貌似后者更强悍一些。

  1. package com.springboot.study;
  2. import org.springframework.boot.CommandLineRunner;
  3. import org.springframework.stereotype.Component;
  4. /**
  5. * Created by lvzhixiang on 2019/12/21.
  6. */
  7. @Component
  8. public class MyCommandLineRunner implements CommandLineRunner{
  9. @Override
  10. public void run(String... var1) throws Exception{
  11. System.out.println("This will be execute when the project was started!");
  12. }
  13. }

ApplicationRunner :

  1. package com.springboot.study;
  2. import org.springframework.boot.ApplicationArguments;
  3. import org.springframework.boot.ApplicationRunner;
  4. import org.springframework.stereotype.Component;
  5. /**
  6. * Created by lvzhixiang on 2019/12/21.
  7. */
  8. @Component
  9. public class MyApplicationRunner implements ApplicationRunner {
  10. @Override
  11. public void run(ApplicationArguments var1) throws Exception{
  12. System.out.println("MyApplicationRunner class will be execute when the project was started!");
  13. }
  14. }

这两种方式的实现都很简单,直接实现了相应的接口就可以了。记得在类上加@Component注解。
如果想要指定启动方法执行的顺序,可以通过实现org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解来实现。

这里我们以ApplicationRunner 为例来分别实现。
Order注解实现方式:

  1. package com.springboot.test;
  2. import org.springframework.boot.ApplicationArguments;
  3. import org.springframework.boot.ApplicationRunner;
  4. import org.springframework.core.Ordered;
  5. import org.springframework.core.annotation.Order;
  6. import org.springframework.stereotype.Component;
  7. /**
  8. * 这里通过设定value的值来指定执行顺序
  9. */
  10. @Component
  11. @Order(value = 1)
  12. public class MyApplicationRunner implements ApplicationRunner{
  13. @Override
  14. public void run(ApplicationArguments var1) throws Exception{
  15. System.out.println("ApplicationRunner1!");
  16. }
  17. }

Ordered接口实现方式:

  1. package com.springboot.test;
  2. import org.springframework.boot.ApplicationArguments;
  3. import org.springframework.boot.ApplicationRunner;
  4. import org.springframework.core.Ordered;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class MyApplicationRunner implements ApplicationRunner,Ordered{
  8. @Override
  9. public int getOrder(){
  10. return 1;//通过设置这里的数字来设置指定顺序
  11. }
  12. @Override
  13. public void run(ApplicationArguments var1) throws Exception{
  14. System.out.println("ApplicationRunner1!");
  15. }
  16. }

发表评论

表情:
评论列表 (有 0 条评论,20人围观)

还没有评论,来说两句吧...

相关阅读