Spring Boot 设置context-path,Spring Boot使用Runner

Spring Boot 设置context-path

SpringBoot 2.0.0.RELEASE版本后更新

  # yml配置
  server:
      servlet:
          context-path: /example

  # properties配置
  server.servlet.context-path=/example

Spring Boot使用Runner

项目启动的时候进行一些一次性的初始化工作
spring-boot中提供了两种Runner接口:ApplicationRunner和CommandLineRunner
新建类 添加注解,@Component实现Runner接口,重写run方法即可。
如果有多个类 @Order(num) 注解可以指定执行顺序 num越小,优先级越高。不设置num,默认最低优先级,因为默认值是int最大值。

ApplicaitonRunner和CommandLineRunner相比,它们虽然都只有一个run接口,但是各自接收的参数类型却不一样,这也是他们唯一的区别。

CommandLineRunner的run方法接收的是一个String类型的可变参数,它的值就是我们main函数接收到的命令行参数。
ApplicaitonRunner的run方法接收一个ApplicationArguments类型的参数,ApplicationArguments会对spring-boot程序的启动参数进行解析和分类,把[--{operation-name}={operation-value}]解析操作参数,其它情况被分类为非操作参数。

Runner的实现原理

spring-boot的runner扩展的实现也是非常的简单的。写过spring-boot程序的朋友一定对SpringApplication.run方法影响深刻,我们今天讲的runner也是在这个方法中被调用的。整个调用过程:

SpringApplication.run调用callRunners方法
查找实现了ApplicationRunner和CommandLineRunner接口的Bean,统一存放在一个list中
根据Bean的order进行排序
循环调用每一个Runner Bean的run接口。

posted @ 2021-02-09 16:43  CalronLoveRonnie  阅读(1158)  评论(0编辑  收藏  举报
AmazingCounters.com