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
관리 메뉴

개발자되기 프로젝트

빈 생명주기 : @Bean(initMethod, destroyMethod) 본문

인프런/[인프런] Spring 핵심원리 이해

빈 생명주기 : @Bean(initMethod, destroyMethod)

Seung__ 2021. 7. 30. 21:23

설정 정보에 초기화, 소멸 메서드 지정이 가능하다.

  • @Bean(initMethod = " ~", destoryMethod = " ~~")

 

1. @Bean 등록


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(initMethod = "init", destroyMethod = "close")
        public NetworkClient networkClient(){
            NetworkClient networkClient = new NetworkClient();
            networkClient.setUrl("http://hello-spring.dev");
            return networkClient;
        }
    }
}

 

 

2. init, close method


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);
    }


    public void init() {
        System.out.println("NetworkClient.init");
        connect();
        call("초기화 연결 메세지");
    }


    public void close()  {
        System.out.println("NetworkClient.close");
        disconnect();
    }
}

 

 

3. 결과


  • 짜잔
생성자 호출, url =null
NetworkClient.init
connect : http://hello-spring.dev
call = http://hello-spring.dev message = 초기화 연결 메세지
21:14:35.829 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@662b4c69, started on Fri Jul 30 21:14:35 KST 2021
NetworkClient.close
close : http://hello-spring.dev

 

 

4. 특징


  • 이름 자유롭게 설정 가능
  • 스프링 빈이 스프링 코드에 의존하지 않음
  • 코드가 아니라 설정 정보를 사용, 코드를 고칠 수 없는 외부 라이브러리에도 적용이 가능하다! ㄱㅇㄷ~

 

 

5. @Bean의 destroyMethod 속성


  • 라이브러리 대부분 close, shutdown이라는 종료 메서드 사용
  • destroyMethod는 기본 값이 (inffered)로 돼있음
  • 즉, 알잘딱으로 close, shutdown을 자동으로 호출해준다는 말.
  • 직접 스프링 빈으로 등록하면, 종료 메서드는 따로 안해도 알잘딱됨
  • 만약 알잘딱이 실으면 destoryMethod = "" 공백으로.

 

 

6. GitHub : 210730 @Bean(initMethod, destroyMethod)


 

GitHub - bsh6463/SpringCoreFunction

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

github.com

 

Comments