일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- SseEmitter
- bean
- server send event
- session
- Stream
- web
- Hibernate
- 생명주기 콜백
- cookie
- jQuery
- programmers
- oauth
- jenkins
- hanghae99
- JWT
- Anolog
- DI
- flask
- python
- javascript
- Project
- html
- WIL
- JPA
- google oauth
- Java
- spring
- 항해99
- Spring Security
- real time web
- Today
- Total
끄적끄적 코딩일지
[Spring 기초] Bean 생명주기 콜백 본문
Bean을 사용하면서 초기화나 Bean 삭제시 발생시켜야할 이벤트를 지정해야할 때가 있다.
예를들어 Socket통신등 네트워크를 사용하는 객체는 프로그램 시작시 특정 Server와 연결하거나 프로그램 종료시 Bean 삭제시 해당 Server와의 연결을 안전하게 종료해야 할 때가 있다. 이처럼 Bean의 초기화나 종료 작업을 관리하는것을 Bean의 생명주기 콜백이라고 한다. 생명주기 콜백에서 초기화 작업은 모든 의존성이 주입된 후 호출된다.
1. Interface를 사용한 방법
Bean으로 등록되는 객체에 특정 Interface를 implement하는 방식으로
초기화는 InitializingBean, 종료는 DisposableBean을 사용하여 구현한다.
@Component
public class NetWork implements InitializingBean,DisposableBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("초기화 작업 실행")
}
@Override
public void destroy() throws Exception {
System.out.println("종료 작업 실행")
}
}
Interface를 사용한 방법에는 다음과 같은 단점이 있다.
1. Spring 전용 Interface라서 해당 코드가 Spring 전용 Interface에 의존한다.
2. 초기화, 소멸 Method의 이름을 변경할 수 없다.
3. 수정할 수 없는 외부 라이브러리등에 적용할 수 없다.
Interface를 사용하는 방법은 Spring 초기에 나온 방법이라 지금은 더 좋은 방법이 있기에 거의 사용하지 않는다.
2. Method를 사용하는 방법
class Network{
public void init(){
System.out.println("초기화 작업 실행");
}
public void close(){
System.out.println("종료 작업 실행");
}
}
@Configuration
class AppConfig{
@Bean(initMethod="init",destoryMethod="close")
public Network getNetwork(){
return new Network();
}
}
Bean을 등록시에 생성, 소멸의 Method를 직접 지정해 주는 방법이다.
Method이름을 자유롭게 설정할 수 있고 외부 라이브러리에도 적용이 가능하다.
참고로 소멸 메소드는 직접 지정을 하지 않아도 자동으로 close(), shutdown() 등의 이름의 Method를 찾아서 실행시킨다.
3. Annotation을 사용하는 방법
@Component
public class NetWork {
@PostConstruct
public void init() {
System.out.println("초기화 작업 실행")
}
@PreDestory
public void destroy() {
System.out.println("종료 작업 실행")
}
}
최신 Spring에서 가장 권장하는 방법으로 간편하게 Annotation만 활용해서 구현 가능하다는 장점이 있다.
하지만 Interface를 활용한 방법처럼 외부 라이브러리에는 적용이 불가능하므로 Method를 사용한 방법과 섞어서 사용하면 될듯하다.
'Spring' 카테고리의 다른 글
[Spring 기초] Scope 사용하기 (0) | 2022.06.07 |
---|---|
[Spring 기초] 트랜잭션 (0) | 2022.06.06 |
[Spring 기초] MVC 패턴 (0) | 2022.06.05 |
[Spring 기초] Hibernate 다루기 (0) | 2022.06.05 |
[Spring 기초] Spring Security 사용하기 (0) | 2022.06.04 |