해결된 질문
작성
·
303
3
hello.core.lifecycle.NetworkClient.java
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);
/*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);
}
@Override
public void afterPropertiesSet() throws Exception {
/* 생성자에 있던 코드를 이곳으로 ---> "생성과 초기화를 분리" */
System.out.println("NetworkClient.afterPropertiesSet");
connect();
call("초기화 연결 메시지");
}
@Override
public void destroy() throws Exception {
System.out.println("NetworkClient.destroy");
System.out.println("destroy() : url = " + url);
disconnect();
}
}
hello.core.lifecycle.BeanLifeCycleTest.java
package hello.core.lifecycle;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
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(NetworkClient.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.net");
return networkClient;
}
}
}
제 코드의 실행 결과
생성자 호출, url = null
NetworkClient.afterPropertiesSet
Connect: null
call: null, message = 초기화 연결 메시지
01:08:27.660 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4a7f959b, started on Fri Dec 11 01:08:27 KST 2020
NetworkClient.destroy
destroy() : url = null
Close: null
답변 4
1
자답입니다. 오타를 찾아서 해결했습니다. 오타는 항상 어처구니가 없네요.
@Test public void lifeCycleTest() 메소드 첫 줄에 LifeCycleConfig.class 여야 하는데, NetworkClient.class 로 적은 부분입니다.
영한님의 소중한 시간을 위해, 답변 달지 않으셔도 됩니다.
감사합니다.
0
0
0