> Java > java지도 시간 > 본문

시작 후 Springboot를 실행하는 방법

WBOY
풀어 주다: 2023-06-03 11:21:39
앞으로
842명이 탐색했습니다.

1. @PostConstruct 주석

@PostConstruct 주석을 사용하는 것이 가장 일반적인 방법입니다. 문제는 실행되는 메서드가 너무 오래 걸리면 메서드 실행 중에 프로젝트가 서비스를 제공할 수 없다는 것입니다.

@Component
public class StartInit {
//
//    @Autowired   可以注入bean
//    ISysUserService userService;

    @PostConstruct
    public void init() throws InterruptedException {
        Thread.sleep(10*1000);//这里如果方法执行过长会导致项目一直无法提供服务
        System.out.println(123456);
    }
}
로그인 후 복사

2. CommandLineRunner 인터페이스

CommandLineRunner 인터페이스를 구현한 후 run 메소드에서 호출해야 할 메소드를 호출하면 해당 메소드가 실행되면 프로젝트가 초기화되어 정상적으로 서비스를 제공할 수 있다는 장점이 있습니다.

동시에 이 메소드는 매개변수도 허용할 수 있으며, 프로젝트가 시작될 때 전달된 매개변수를 기반으로 일부 처리를 수행할 수 있습니다: java -jar 데모.jar arg1 arg2 arg3.

@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(Arrays.toString(args));
    }
}
로그인 후 복사

3. ApplicationRunner 인터페이스 구현

ApplicationRunner와 CommandLineRunner의 구현 방법은 기본적으로 유사합니다.

유일한 차이점은 시작 시 전달되는 매개변수 형식입니다. ApplicationRunner 인터페이스 매개변수 형식은 –key=value

@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        Set<String> optionNames = args.getOptionNames();
        for (String optionName : optionNames) {
            List<String> values = args.getOptionValues(optionName);
            System.out.println(values.toString());
        }
    }
}
로그인 후 복사

Four 인터페이스 ApplicationListener 메소드를 구현해야 합니다. 그리고 ApplicationRunner를 구현합니다. CommandLineRunner 인터페이스는 서비스에 영향을 미치지 않으며 일반적으로 모니터링되는 이벤트(일반적으로 ApplicationStartedEvent 또는 ApplicationReadyEvent)에 주의하세요.

@Component
public class ApplicationListenerImpl implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println("listener");
    }
}
로그인 후 복사

5. 네 가지 메소드의 실행 순서

@PostConstruct 주석 메소드가 항상 먼저 실행됩니다.

ApplicationStartedEvent 이벤트가 모니터링되면 CommandLineRunner 및 ApplicationRunner보다 먼저 실행됩니다.

ApplicationReadyEvent 이벤트를 듣고 있다면 반드시 CommandLineRunner 및 ApplicationRunner 다음에 실행될 것입니다.

CommandLineRunner 및 ApplicationRunner는 기본적으로 ApplicationRunner가 먼저 실행됩니다. 두 당사자 모두 @Order를 지정하면 @Order 크기 순서대로 실행되며 더 큰 것이 먼저 실행됩니다.

위 내용은 시작 후 Springboot를 실행하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:yisu.com
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!