一、程序启动时执行顺序
…
Constructor
…
@Autowired
…
@PostConstruct
…
ApplicationRunner
CommandLineRunner
ApplicationListener < ApplicationReadyEvent >
…
@Slf4j
@RequiredArgsConstructor
@Order(4)
public class Test1 {
@PostConstruct
public void run() {
log.info("PostConstruct "+ LocalDateTime.now());
}
}
@Slf4j
@RequiredArgsConstructor
@Order(3)
public class Test2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("ApplicationRunner "+ LocalDateTime.now());
}
}
@Slf4j
@RequiredArgsConstructor
@Order(2)
public class Test3 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("CommandLineRunner "+ LocalDateTime.now());
}
}
@Slf4j
@RequiredArgsConstructor
@Order(1)
public class Test4 implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
log.info("ApplicationReadyEvent "+ LocalDateTime.now());
}
}
运行结果:
...Test1 : PostConstruct 2020-06-29T16:12:05.364242200
...Test2 : CommandLineRunner 2020-06-29T16:12:16.884044900
...Test3 : ApplicationRunner 2020-06-29T16:12:16.884044900
...Test4 : ApplicationReadyEvent 2020-06-29T16:12:16.885044200
这里使用@Order来指定运行顺序时, 只会对ApplicationRunner和CommandLineRunner起作用