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

개발자되기 프로젝트

@PostConstruct, @PreDestroy 본문

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

@PostConstruct, @PreDestroy

Seung__ 2021. 7. 30. 21:46

1. 빈 생성, 의존성 주입 후 실행할 method 지정 : @PostConstruct

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

2. 빈 소면 전에 실행할 method 지정 : @PreDestroy

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

3. Test

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

아 깔끔

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

 

4. @PostConstruct, @PreDestroy

  • 스프링에서 권장함 
  • 개편함
  • javax.annotation.PostConstruct이다. 스프링에 종속이 아니라 java 표준이다.
  • 컴포넌트 스캔과 잘 어울린다?
  • 단점은... 외부 라이브러리에 적용 못해..
  • 외부 라이브러리를 초기화, 종료해야 하면 @Bean기능을 사용하자.
 

빈 생명주기 : 초기화, 소멸 메서드 지정!

설정 정보에 초기화, 소멸 메서드 지정이 가능하다. @Bean(initMethod = " ~", destoryMethod = " ~~") 1. @Bean 등록 public class BeanLifeCycleTest { @Test public void lifeCycleTest(){ AnnotationConfigApp..

bsh-developer.tistory.com

 

5. GitHub : 210730 @PostConstruct, @PreDestroy


 

GitHub - bsh6463/SpringCoreFunction

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

github.com

 

Comments