Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Archives
Today
Total
관리 메뉴

개발자되기 프로젝트

인터페이스 : InitializingBean, DisposableBean 본문

카테고리 없음

인터페이스 : InitializingBean, DisposableBean

Seung__ 2021. 7. 30. 21:07

1. InitializingBean(초기화)


  • 의존성 주입 완료후 초기화 메서드 제공
  • afterPropertiesSet() : 의존관계 주입 완료후 실행됨.

 

 

2. DisposableBean(소멸)


  • 빈 소멸되기 직전 실행하는 메서드 제공
  • destroy()

 

 

3. Test


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 {
        System.out.println("NetworkClient.afterPropertiesSet");
        connect();
        call("초기화 연결 메세지");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("NetworkClient.destroy");
        disconnect();
    }
}
public class BeanLifeCycleTest {

    @Test
    public void lifeCycleTest(){
        AnnotationConfigApplicationContext 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;
        }
    }
}

실행 결과

  • 의존성 주입이 완료된 후 afterPropertiesSet 실행
  • 스프링 컨테이너가 내려갈 때 detroy 호출.
생성자 호출, url =null
NetworkClient.afterPropertiesSet
connect : http://hello-spring.dev
call = http://hello-spring.dev message = 초기화 연결 메세지
20:59:49.938 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@4d0f2471, started on Fri Jul 30 20:59:49 KST 2021
NetworkClient.destroy
close : http://hello-spring.dev

 

 

4. 초기화, 소멸 인터페이스 단점


  • 스프링 전용 인터페이스 ㅋㅋㅋㅋ코드가 스프링 전용 인터페이스에 의존하게됨..
  • 초기화 소멸 메서드 이름을 바꿀 수 도 없음
  • 외부 라이브러리에 적용도 불가..

근데 지금은 잘 안씀 ㅋㅋㅋㅋ

 

 

5. GitHub : 210730 빈 생성,소멸 인터페이스


 

GitHub - bsh6463/SpringCoreFunction

Contribute to bsh6463/SpringCoreFunction development by creating an account on GitHub.

github.com

 

Comments