💻본 포스팅은 '스프링 핵심 원리 - 기본편 김영한'님의 강의를 듣고 작성되었습니다.
스프링 핵심 원리 - 기본편 - 인프런 | 강의
스프링 입문자가 예제를 만들어가면서 스프링의 핵심 원리를 이해하고, 스프링 기본기를 확실히 다질 수 있습니다., - 강의 소개 | 인프런...
www.inflearn.com
1. 빈 생명주기
[빈 생명주기 - Bean Life Cycle]
컨테이너 생성 👉 스프링 빈 생성 👉 의존관계 주입 👉 초기화 콜백 👉 사용 👉 소멸 전 콜백 👉 스프링 종료
이 과정을 통해서 빈 생성 후 의존관계 주입이 다 끝나고나서 초기화, 종료 작업을 해야 하는데, 객체가 생성되는 과정이나 의존관계 주입이 끝나지 않았을 때 초기화를 해주게 되면 문제가 발생하게 된다.
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-spring.dev");
return networkClient;
}
}
}
package hello.core.lifecycle;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class NetworkClient{
private String url;
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);
}
}
- 기존의 빈 생명주기를 알아보기 위해서 작성한 클래스와 그를 확인하기 위한 테스트 코드이다.
- 생성자 부분을 보면 url 정보 없이 connect가 호출되는 것을 확인할 수 있다. 너무 당연한 이야기이지만 객체를 생성하는 단계에는 url이 없고, 객체를 생성한 다음에 외부에서 수정자 주입을 통해서 setUrl() 이 호출되어야 url이 존재하게 된다
2. 콜백
[초기화, 종료 콜백]
- 초기화 콜백: 빈이 생성되고, 빈의 의존관계 주입이 완료된 후 호출
- 소멸전 콜백: 빈이 소멸되기 직전에 호출
스프링은 크게 3가지 방법으로 빈 생명주기 콜백을 지원한다.
- 인터페이스(InitializingBean, DisposableBean)
- 설정 정보에 초기화 메서드, 종료 메서드 지정
- @PostConstruct, @PreDestroy 애노테이션 지원
[초기화 종료 인터페이스]
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-spring.dev");
return networkClient;
}
}
}
package hello.core.lifecycle;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class NetworkClient implements InitializingBean, DisposableBean {
private String url;
public NetworkClient(){
System.out.println("생성자 호출, url = " + url);
}
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);
}
@Override
public void afterPropertiesSet() throws Exception{
connect();
call("초기화 연결 메시지");
}
@Override
public void destroy() throws Exception{
disconnect();
}
}
[초기화 종료 인터페이스 단점]
- 스프링에서 제공하는 스프링 인터페이스로 매우 스프링에 의존적이다.
- 수정 불가한 외부 라이브러리를 사용할 때 적용할 수 없다.
- 메소드 명을 직접 작성 불가하다.(afterPropertiesSet( ), destroy( )로 고정)
[설정 정보에 초기화 메서드, 종료 메서드 지정]
설정 정보에 @Bean(initMethod = "init", destroyMethod = "close") 처럼 초기화, 소멸 메서드를 지정할 수 있다
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(initMethod = "init", destroyMethod = "close")
public NetworkClient networkClient(){
NetworkClient networkClient = new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
}
[설정 정보 사용 특징]
- 메서드 이름을 자유롭게 줄 수 있다.
- 스프링 빈이 스프링 코드에 의존하지 않는다.
- 코드가 아닌 설정 정보 사용을 하기 때문에 코드를 고칠 수 없는 외부 라이브러리에도 초기화와 종료 메서드를 적용할 수 있다.
[종료 메서드 추론]
destroyMethod는 추론 기능이 있기에 close, shutdown 이라는 종료 메서드를 대부분 사용하는 라이브러리들 때문에 이들을 자동으로 호출하고 이름 그대로 종료 메서드를 추론해서 호출해준다.
[애노테이션 @PostConstruct, @PreDestroy]
실제로 이 방법을 제일 권고하고 있다고 한다.
package hello.core.lifecycle;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class NetworkClient{
private String url;
public NetworkClient(){
System.out.println("생성자 호출, url = " + url);
}
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);
}
@PostConstruct
public void init() {
System.out.println("NetworkClient.init");
connect();
call("초기화 연결 메시지");
}
@PreDestroy
public void close(){
System.out.println("NetworkClient.close");
disconnect();
}
}
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
- 자바에서 지원하기 때문에 스프링이 아니더라도 사용이 가능하다.
- 자바 표준에서 지원해서 스프링 아닌 다른 곳에서도 사용이 가능하고 스프링에 의존적이지 않음
- 애노테이션만 붙이면 되기 때문에 매우 편리하다.
- 이 방법을 사용하는 것이 최고 BEST!!!
[애노테이션 @PostConstruct, @PreDestroy 단점]
- 외부 라이브러리에 사용할 수 없다는 단점이 있지만 이때는 @Bean(initMethod = "init", destroyMethod = "close")이 방법을 사용해주면 된다.
'Back-End > Spring' 카테고리의 다른 글
[Spring][스프링 기본편] - 27. 웹 스코프 (0) | 2022.02.07 |
---|---|
[Spring][스프링 기본편] - 26. 빈 스코프 (0) | 2022.02.04 |
[Spring][스프링 기본편] - 24. 조회 빈이 2개 이상일 때와 해결법(@ Autowired, @Qualifier, @Primary) (0) | 2022.01.31 |
[Spring][스프링 기본편] - 23. 롬복(Lombok)과 최신 트렌드 (0) | 2022.01.31 |
[Spring][스프링 기본편] - 22. 생성자 주입을 사용해야 하는 이유(의존관계 설정) (0) | 2022.01.28 |