programing

Application Runner 및 Runner 인터페이스가 필요한 시기와 이유는 무엇입니까?

fastcode 2023. 4. 5. 22:19
반응형

Application Runner 및 Runner 인터페이스가 필요한 시기와 이유는 무엇입니까?

봄 부츠를 배우고 있어요.ApplicationRunner 또는 Runner 인터페이스의 일반적인 사용 사례는 무엇입니까?

import org.junit.jupiter.api.Test;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class PersistencedemoApplicationTests implements ApplicationRunner {

    @Test
    void contextLoads() {
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
       // load initial data in test DB
    }
}

이건 내가 알고 있는 사건 중 하나야.또 다른 건 없으세요?

이러한 러너는 어플리케이션 부팅 시 로직을 실행하기 위해 사용됩니다.예를 들어 스프링 부트에는 어플리케이션러너(기능 인터페이스)가 있습니다.run방법

ApplicationRunner run()은 어플리케이션 컨텍스트가 생성된 직후와 스프링 부트 어플리케이션이 시작되기 전에 실행됩니다.

ApplicationRunner는 getOptionNames(), getOptionValues() 및 getSourceArgs()와 같은 편리한 메서드를 가진 ApplicationArgument를 사용합니다.

또한 CommandLineRunner는 다음 기능을 가진 인터페이스입니다.run방법

CommandLineRunner run()은 어플리케이션 컨텍스트가 작성된 직후와 스프링 부트 어플리케이션이 시작되기 전에 실행됩니다.

서버 부팅 시 전달되는 인수를 받아들입니다.

둘 다 같은 기능을 제공하지만 이 두 가지 차이점이 있습니다.CommandLineRunner그리고.ApplicationRunnerCommandLineRunner.run()받아들이다String array[]반면에.ApplicationRunner.run()받아들이다ApplicationArguments의론으로서예시를 통해 자세한 정보를 여기서 찾을 수 있습니다.

ApplicationRunner 또는 CommandLineRunner 인터페이스를 사용하려면 Spring bean을 생성하여 ApplicationRunner 또는 CommandLineRunner 인터페이스 중 하나를 구현해야 합니다.이 두 인터페이스는 모두 동일하게 실행됩니다.완료되면 Spring 어플리케이션이 콩을 검출합니다.

또한 Application Runner 또는 Command Line Runner 콩을 여러 개 작성하고 다음 중 하나를 구현하여 순서를 제어할 수 있습니다.

  • org.springframework.core.순서부 인터페이스

  • org.springframework.core.information 입니다.주석을 정렬합니다.

사용 사례:

  1. 명령줄 인수를 기록할 수 있습니다.

  2. 이 애플리케이션의 종료시에, 유저에게 몇개의 순서를 제공할 수 있습니다.

고려사항:

@Component
public class MyBean implements CommandLineRunner {

    @Override
    public void run(String...args) throws Exception {
        logger.info("App started with arguments: " + Arrays.toString(args));
    }
}

Application Runner 세부 사항

ApplicationRunner와 CommandLineRunner는 응용 프로그램이 완전히 시작되기 직전에 커스텀코드를 실행하기 위해 스프링부트가 제공하는2개의 인터페이스입니다.

스프링 배치는 배치 처리 프레임워크입니다.이 명령어는 CommandLineRunner를 사용하여 애플리케이션 부팅 시 배치 작업을 등록하고 시작합니다.

이 인터페이스를 사용하여 일부 마스터 데이터를 캐시에 로드하거나 상태 점검을 수행할 수도 있습니다.

사용 사례는 응용 프로그램에 따라 다릅니다.

또는 다음과 같이 합니다.

@Bean
ApplicationRunner appStarted() {
    return args -> {
        logger.info("Ready to go - args: {}", args.getNonOptionArgs());
    };
}

언급URL : https://stackoverflow.com/questions/59328583/when-and-why-do-we-need-applicationrunner-and-runner-interface

반응형