springcloud项⽬的启动顺序_SpringCloud(27)——
Springboo。。。
Springboot给我们提供了两种“开机启动”某些⽅法的⽅式:ApplicationRunner和CommandLineRunner。
这两种⽅法提供的⽬的是为了满⾜,在项⽬启动的时候⽴刻执⾏某些⽅法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执⾏之后开始执⾏的。
CommandLineRunner接⼝可以⽤来接收字符串数组的命令⾏参数,ApplicationRunner 是使⽤ApplicationArguments ⽤来接收参数
的,貌似后者更⽜逼⼀些。
CommandLineRunner的实现⽅式:
packagecom.springboot.study;importorg.springframework.boot.CommandLineRunner;importorg.springframework.stereotype.C
@Componentpublic class MyCommandLineRunner implementsCommandLineRunner{
@Overridepublic void var1) throwsException{
System.out.println("This will be execute when the project was started!");
}
}
ApplicationRunner的实现⽅式:
packagecom.springboot.study;importorg.springframework.boot.ApplicationArguments;importorg.springframework.boot.Applica
@Componentpublic class MyApplicationRunner implementsApplicationRunner {
@Overridepublic void run(ApplicationArguments var1) throwsException{
System.out.println("MyApplicationRunner class will be execute when the project was started!");
}
}
这两种⽅式的实现都很简单,直接实现了相应的接⼝就可以了。记得在类上加@Component注解。
如果想要指定启动⽅法执⾏的顺序,可以通过实现Ordered接⼝或者使⽤
annotation.Order注解来实现。
如果有多个要执⾏的⽅法@Order 这个注释来规定执⾏的先后顺序. 数字越⼩优先级越⾼
这⾥我们以ApplicationRunner为例分别实现:
1、Ordered接⼝
packagecom.springboot.study;importorg.springframework.boot.ApplicationArguments;importorg.springframework.boot.Applica
@Componentpublic class MyApplicationRunner implementsApplicationRunner,Ordered{
@Overridepublic intgetOrder(){return 1;//通过设置这⾥的数字来知道指定顺序
}
@Overridepublic void run(ApplicationArguments var1) throwsException{
System.out.println("MyApplicationRunner1!");
}
}
2、Order注解实现⽅式:
packagecom.springboot.study;importorg.springframework.boot.ApplicationArguments;importorg.springframework.boot.Applica 这⾥通过设定value的值来指定执⾏顺序*/@Component
@Order(value= 1)public class MyApplicationRunner implementsApplicationRunner{
@Overridepublic void run(ApplicationArguments var1) throwsException{
System.out.println("MyApplicationRunner1!");
springboot是啥}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。