개발자의 무지개

Spring Boot - Bean 객체 생성 시점 본문

프로그래밍/Spring boot

Spring Boot - Bean 객체 생성 시점

파란막대 2022. 7. 5. 00:54

지난 시간에 restful api 로 get 메서드 호출하는 코드를 작성하였다.

 

2022.07.03 - [프로그래밍/Java & Spring] - Spring Boot - 웹 프로젝트 생성

 

Spring Boot - 웹 프로젝트 생성

맥북에 이클립스를 설치후 마켓에서 Spring Boot 를 내려받았다. 웹 프로젝트를 생성하여 간단한 Rest api 프로젝트를 만들어보자. 1. 웹 프로젝트 생성 File 메뉴 -> New -> Other 를 클릭한다. 'spring' 을 입

bluestickvic.tistory.com

 

나는 restApiController 클래스를 생성하지 않았지만, 스프링 컨테이너에서 자동으로 객체를 생성하여 서비스 요청시 해당경로("/rest")에 있는 메서드까지 호출해 주었다.

 

그러면 내가 만든 클래스는 언제 생성(메모리에 로드)되어 소멸(메모리에서 해제)되는 것일까?

 

테스트를 위해 코드를 아래와 같이 변경하였다.

 

package com.jabez.saturn;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;


@SuppressWarnings("unused")  //사용하지 않는 코드의 경고 무시 
@RestController
public class restApiController{
	
	public restApiController() {
		System.out.println("생성자 호출");
	}
	
	public void finalize() {
		System.out.println("소멸자 호출");
	}
	
	@GetMapping("/rest")
	public String welcome() {
		System.out.println("Welcome 호출");
		return "welcome!!";
	}
	
	
}

 

프로젝트를 실행하면 아래와 같이 메시지가 출력된다.

 

 

로그를 순서대로 보면 스프링 부트 실행 -> 아파치 톰캣 구동 -> restApiController 객체 생성 순으로, 서비스 요청과 별개로 스프링 부트 실행시 객체까지 생성한다는 것을 알 수 있다.

 

이제 브라우저에서 서비스 요청을 해보자.

브라우저에서 http://localhost:8080/rest 을 입력하였다.

최초 호출시 DispatcherServlet 이 초기화되고, welcome() 메서드가 호출되었다.

 

순서를 다시 정리해보자.

스프링 부트 실행 -> 아파치 톰캣 구동 ->  restApiController 객체 생성 -> 최초 서비스 요청 -> DispatcherServlet 초기화 -> restApiController 내 메서드 호출 

 

소멸자가 호출되지 않는 이유는 restApiController 객체는 싱글톤으로 생성되어 스프링 컨테이너에 등록되는데, 객체의 소멸을 위해서는 스프링 컨테이너가 종료되어야 하기 때문이다.