[Spring Boot] ApplicationRunner 등록 방법 정리

2021. 4. 22. 03:22 Spring Framework/Spring boot #3

 

[Spring Boot] ApplicationRunner 등록 방법 정리

1. 별도의 클래스에 @Component 붙여서 등록하기

import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;

@Component
public class ApplicationRunner implements org.springframework.boot.ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        
        // 코드 작성
    }
}

 

2. @Configuration 클래스에 @Bean으로 직접 등록하기

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ExceptionhandlerExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExceptionhandlerExampleApplication.class, args);
    }

    @Bean
    public ApplicationRunner applicationRunner() {
        return new ApplicationRunner() {
            @Override
            public void run(ApplicationArguments args) throws Exception {
            
            	// 코드 작성
            }
        };
    }
}

 

3. Lambda를 이용해서 등록하기

2번 방법에서 lambda식으로 변경한 방법이다.

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ExceptionhandlerExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(ExceptionhandlerExampleApplication.class, args);
    }

    @Bean
    public ApplicationRunner applicationRunner() {
        return args -> {

			// 코드 작성
        };
    }
}

 

출처 : atoz-develop.tistory.com/entry/Spring-Boot-ApplicationRunner-%EB%93%B1%EB%A1%9D-%EB%B0%A9%EB%B2%95-%EC%A0%95%EB%A6%AC?category=869242