>  기사  >  Java  >  springboot 프로젝트가 시작된 후 실행 방법은 무엇입니까?

springboot 프로젝트가 시작된 후 실행 방법은 무엇입니까?

王林
王林앞으로
2023-05-27 23:16:461988검색

1 메서드

  • ApplicationListenerf4b06c38ff2750052547656f66f34e34 권장되지 않음

  • ApplicationListener 권장

  • CommandLineRunner 권장

방법 1: Spring의 ApplicationListener& lt; shedEvent> 인터페이스

는 ApplicationListener 인터페이스를 구현하고 onApplicationEvent(ContextRefreshedEvent를 구현합니다. contextRefreshedEvent) method

@Service
public class SearchReceive implements  ApplicationListener<ContextRefreshedEvent> {
   @Override
   public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
       if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
           //需要执行的方法
       }
   }
}

Method 2: springboot의 ApplicationRunner 인터페이스

ApplicationListener와 CommandLineRunner는 spring 컨테이너가 로드된 후 지정된 메서드를 실행하기 위해 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 및 CommondLineRunner 인터페이스가 모두 프로젝트에 구현되면 Order 주석을 사용하거나 Ordered 인터페이스를 구현하여 실행 순서를 지정할 수 있습니다. 더 일찍 실행됩니다.

3 원리

SpringApplication의 run 메소드는 afterRefresh 메소드를 실행합니다.

afterRefresh 메소드는 callRunners 메소드를 실행합니다.

callRunners 메서드는 ApplicationRunner 및 CommondLineRunner 인터페이스를 구현하는 모든 메서드를 호출합니다.

위 내용은 springboot 프로젝트가 시작된 후 실행 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제