Springboot 프로젝트가 시작된 후 실행 방법을 구현하는 방법에는 세 가지가 있습니다.
본 블로그에서 소개하는 방법은 프로그램이 시작될 때 소켓 서비스의 리스너와 같은 일부 사용자 정의 리스너를 로드할 수 있는데, 이때 @PostConstract를 사용하면 소켓 서비스의 리스너가 시작 프로그램을 차단하여 프로그램이 작동하지 않게 됩니다. 실패. 시작.
1 메소드
ApplicationListener< ContextRefreshedEvent>
ApplicationListener 는 권장되지 않음,
CommandLineRunner는 권장됨
메소드 1: Spring의 ApplicationListener< ContextRefreshedEvent> 인터페이스는
ApplicationListener 인터페이스를 구현하고 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) 메소드를 구현함
@Service
public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
//需要执行的方法
}
}
}
방법 2: Springboot의 ApplicationRunner 인터페이스
ApplicationRunner와 CommandLineRunner는 스프링 컨테이너가 로드된 후 지정된 메서드를 실행하기 위해 springBoot에서 제공하는 두 가지 인터페이스입니다. 두 인터페이스의 차이점은 주로 입력 매개변수입니다.
ApplicationRunner 인터페이스 구현
@Component
@Order(value = 1)
public class AfterRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("执行方法");
}
}
방법 3: springboot의 CommandLineRunner 인터페이스
CommandLineRunner 인터페이스 구현
@Component
@Order(value = 2)
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("执行方法");
}
}
참고: ApplicationListener와 CommandLineRunner를 동시에 구현하는 경우 ApplicationRunner 인터페이스의 메서드가 먼저 실행되고 이어서 CommandLineRunner가 실행됩니다.
@Slf4j
@Component
public class RunnerTest implements ApplicationRunner, CommandLineRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("服务启动RunnerTest ApplicationRunner执行启动加载任务...");
}
@Override
public void run(String... args) throws Exception {
System.out.println("服务启动RunnerTest CommandLineRunner 执行启动加载任务...");
}
}
}
2 실행 순서 지정
프로젝트에 ApplicationRunner 및 CommonLineRunner 인터페이스가 모두 구현된 경우 Order 주석을 사용하거나 Ordered 인터페이스를 구현하여 실행 순서를 지정할 수 있으며, 값이 작을수록 일찍 실행됩니다.
3 원리
SpringApplication의 run 메소드는 afterRefresh 메소드를 실행합니다.
afterRefresh 메소드는 callRunners 메소드를 실행합니다.
callRunners 메소드는 ApplicationRunner 및 CommonLineRunner 인터페이스를 구현하는 모든 메소드를 호출합니다.
————————————————
저작권 표시: 이 글은 CC 4.0 BY-SA 저작권 계약을 준수하는 CSDN 블로거 "사향고양이"의 원본 글입니다. 링크와 이 성명을 재인쇄합니다.
원본 링크: https://blog.csdn.net/m0_56726104/article/details/124931815