728x90
1. 어노테이션 사용
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public class NetworkClient {
private String url;
/ ** 대충 코드 **/
@PostConstruct
public void init(){
System.out.println("NetworkClient.afterPropertiesSet");
connect();
call("초기화 연결 메시지");
}
@PreDestroy
public void close(){
System.out.println("NetworkClient.destroy");
disconnect();
}
}
// 다른 .java에서 NetworkClient 사용
@Configuration
static class LifeCyclConfig{
@Bean
public NetworkClient networkClient(){
NetworkClient networkClient =new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
@Beam 어노테이션에서 직접 지정
@Configuration
static class LifeCyclConfig{
@Bean(initMethod = "init" ,destroyMethod = "close")
public NetworkClient networkClient(){
NetworkClient networkClient =new NetworkClient();
networkClient.setUrl("http://hello-spring.dev");
return networkClient;
}
}
@PostConstruct, @PreDestroy 어노테이션을 사용하자
코드를 고칠 수 없는 외부 라이브러리를 최기화 종료해야 하면 @Bean의 initMethod, destroyMethod를 사용하자
728x90
'백엔드 > Spring(Boot)' 카테고리의 다른 글
| 스프링 웹 설정 (0) | 2021.08.16 |
|---|---|
| 빈 스코프 (0) | 2021.08.16 |
| @Autowired 옵션 (0) | 2021.08.13 |
| 컴포넌트 스캔 필터 (@ComponentScan) (0) | 2021.08.12 |
| @ComponentScan (0) | 2021.08.12 |