@Component를 붙인 코드

@Component
public class DataProcessorScheduler {

    private final FinalMatchService finalMatchService;
    private final LikeablePersonRepository likeablePersonRepository;

    private final MatchMaker matchMaker;
    private final FinalMatchRepository finalMatchRepository;
    private final UserRepository userRepository;

    public DataProcessorScheduler(FinalMatchService finalMatchService, LikeablePersonRepository likeablePersonRepository, MatchMaker matchMaker, FinalMatchRepository finalMatchRepository, UserRepository userRepository){
        this.finalMatchService = finalMatchService;
        this.likeablePersonRepository = likeablePersonRepository;
        this.matchMaker = matchMaker;
        this.finalMatchRepository = finalMatchRepository;
        this.userRepository = userRepository;
    }

    @Transactional
    @Scheduled(cron = "0 0 02 * * ?") // 매일 `새벽 2시 마다
    public void processMatchDate(){
        // user 디비에 있는 모든 유저들 로드해서 수행
       List<User> users = userRepository.findAll();
       for(User user: users){
           // 모든 사용자에 대해 소개 상대 소개 초기화
           matchMaker.manageMatches(user);
       }
        System.out.println("Data processing job executed!!!!!!!!");

    }

    @Transactional
    @Scheduled(cron = "0 */5 * * * *") // 매일 5분 마다
    public void processFinalMatchDate(){

        // user 디비에 있는 모든 유저들 로드해서 수행
        List<User> users = userRepository.findAll();
        for(User user: users){
            // 모든 사용자에 대해 최종 매칭 저장
            finalMatchService.saveFinalMatch(user.getUserId());
        }

        System.out.println("Data processing job executed!!!!!!!!");

    }

}

@Component를 붙인 이유

@Component
public class DataProcessorScheduler {
    // ...
}

@Component 어노테이션은 스프링 프레임워크에서 Java클래스를 스프링 컴포넌트 또는 빈으로 표시하는데 사용된다.

@Component를 클래스에 추가함으로써 스프링에게 해당 클래스의 인스턴스를 생성하고 라이프사이클을 스프링 빈으로 관리하도록 지시한다.

public DataProcessorScheduler(FinalMatchService finalMatchService, LikeablePersonRepository likeablePersonRepository, MatchMaker matchMaker, FinalMatchRepository finalMatchRepository, UserRepository userRepository){
    // ...
}

이렇게 하면 스프링은 DataProcessorScheduler의 인스턴스를 생성하고, 생성자에 명시된 필요한 의존성을 주입할 수 있다.

이렇게 등록된 DataProcessorScheduler 빈은 스프링 애플리케이션 컨텍스트에서 자동으로 검색되어 등록되며, 이는 일반적으로 애플리케이션이 시작될 때 컴포넌트 스캔이 수행될 때 발생한다.

빈이 등록되면 스프링은 @Scheduled어노테이션에 의해 정의된 예약된 작업을 실행하는 데 사용될 수 있다.

DataProcessorScheduler빈과 @Scheduled어노테이션이 붙은 메서드의 관계

DataProcessorScheduler빈이 등록되었기 때문에 @Scheduled어노테이션이 붙은 메서드가 애플리케이션이 시작될 때 자동으로 실행될 수 있다.

🧐@Scheduled어노테이션이 붙은 메서드가 애플리케이션 시작 시 자동으로 실행되는 원리

  1. 스프링 컨텍스트 초기화: 애플리케이션이 시작되면 스프링은 **ApplicationContext**라고 불리는 컨테이너를 초기화합니다. 이 컨테이너는 애플리케이션의 빈들을 관리하고, 빈들 간의 의존성을 주입해줍니다.
  2. @Component 스캔: 스프링은 @ComponentScan 설정을 통해 애플리케이션 패키지를 스캔하고, @Component 어노테이션이 붙은 클래스들을 찾아냅니다. 이때 DataProcessorScheduler 클래스가 해당됩니다.