애플리케이션 종료 시점에 연결을 모두 종료하는 작업을 진행하려면
객체 초기화와 종료 작업이 필요하다.
예제 코드
package hello.core.lifecycle;
public class NetworkClient {
private String url;
// default constructor
public NetworkClient() {
System.out.println("생성자 호출, url = " + url);
connect();
call("초기화 연결 메시지");
}
public void setUrl(String url) {
this.url = url;
}
// 서비스 시작시 호출
public void connect() {
System.out.println("connect: " + url);
}
public void call(String message) {
System.out.println("call: " + url + " message = " + message);
}
// 서비스 종료시 호출
public void disconnect() {
System.out.println("close: " + url);
}
}
스프링 환경설정과 실행
package hello.core.lifecycle;
import org.junit.jupiter.api.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class BeanLifeCycleTest {
@Test
public void lifeCycleTest(){
ConfigurableApplicationContext ac = new AnnotationConfigApplicationContext(LifeCycleConfig.class);
NetworkClient client = ac.getBean(NetworkClient.class);
ac.close();
}
@Configuration
static class LifeCycleConfig {
@Bean
public NetworkClient networkClient() {
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello.dev");
return networkClient;
}
}
}
결과
생성자 호출, url = null
connect: null
call: null message = 초기화 연결 메시지
url 정보 없이 connect가 호출된다.
객체를 생성할땐 url이 없고 생성한 다음 외부에서 수정자 주입을 통해 setUrl()이 호출되어야 들어오기 때문이다.
객체생성 -> 의존관계 주입
생성자 주입은 예외
스프링은 의존관계 주입이 완료되면 스프링 빈에게 콜백 메서드를 통해서 초기화 시점을 알려주는 다양한 기능을 제공한다.
싱글톤일떄
스프링 컨테이너 생성 -> 스프링빈 생성 -> 의존관계 주입 -> 초기화 콜백 -> 사용 -> 소멸전 콜백 -> 종료
객체의 생성과 초기화는 분리하는 것이 좋다.
단일책임의 원칙에 따라 객체 생성에는 생성에만 집중해야 한다.
'Spring' 카테고리의 다른 글
| [Spring] 빈 스코프 (0) | 2026.01.04 |
|---|---|
| [Spring] 빈 생명주기 콜백 - 2 (0) | 2025.12.29 |
| [Spring] 의존관계 자동 주입 - 3 (0) | 2025.12.14 |
| [Spring] 의존관계 자동 주입 - 2 (0) | 2025.12.12 |
| [Spring] 옵션 처리 (0) | 2025.12.09 |