springboot原理pdf
springboot项⽬启动成功后执⾏⼀段代码的两种⽅式springboot项⽬启动成功后执⾏⼀段代码的两种⽅式
实现ApplicationRunner接⼝
package com.lnjecit.lifecycle;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import annotation.Order;
import org.springframework.stereotype.Component;
/**
* @author lnj
* createTime 2018-11-07 22:37
**/
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("通过实现ApplicationRunner接⼝,在spring boot项⽬启动后打印参数");
String[] sourceArgs = SourceArgs();
for (String arg : sourceArgs) {
System.out.print(arg + " ");
}
System.out.println();
}
}
项⽬启动后,会打印如下信息:
实现CommandLineRunner接⼝
package com.lnjecit.lifecycle;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* @author lnj
* createTime 2018-11-07 22:25
**/
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void args) throws Exception {
System.out.println("通过实现CommandLineRunner接⼝,在spring boot项⽬启动后打印参数");
for (String arg : args) {
System.out.print(arg + " ");
}
System.out.println();
}
}
两种实现⽅式的不同之处在于run⽅法中接收的参数类型不⼀样
指定执⾏顺序
当项⽬中同时实现了ApplicationRunner和CommondLineRunner接⼝时,可使⽤Order注解或实现Ordered接⼝来指定执⾏顺序,值越⼩越先执⾏
原理
通过调试可以发现都是在 org.springframework.boot.SpringApplication#run(java.)⽅法内的afterRefresh(上下⽂刷新后处理)⽅法时,会执⾏callRunners⽅法。afterRefresh⽅法具体实现如下:
protected void afterRefresh(ConfigurableApplicationContext context,
ApplicationArguments args) {
callRunners(context, args);
}
callRunners⽅法具体实现如下:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<Object>();
runners.BeansOfType(ApplicationRunner.class).values());
runners.BeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<Object>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
可以看出上下⽂完成刷新后,依次调⽤注册的runners, runners的类型为 ApplicationRunner 或 CommandLineRunner 案例地址
参考资料

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