Spring Application을 구동할 때 메서드를 실행시키는 방법

jaeyong Lee·2024년 8월 7일

필요한 이유

처음에 spring이 실행되면서 초기에 필요한 설정들을 초기화 하는데 사용된다.

흐름)
과거에는 web.xml에서 초기화해줬지만 현대에는 어노테이션 방식으로 흘러간다.

web.xml

어노테이션 방식

@PostConstruct 애노테이션:

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        // 초기화 작업
        System.out.println("Bean is initialized!");
    }
}

CommandLineRunner 및 ApplicationRunner 인터페이스:

@Component
public class MyRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        // 애플리케이션 시작 후 실행할 작업
        System.out.println("Application has started!");
    }
}

Java Configuration (자바 기반 설정):

@Configuration
public class AppConfig {

    @Bean(initMethod = "init")
    public MyBean myBean() {
        return new MyBean();
    }
}

무엇을 초기화?

초기 DB설정(connection pool), 외부 api설정, 캐시 초기화(redis), 보안, 파일 시스템

0개의 댓글