Spring @PostConstructor란?

in #springboot7 years ago

스프링은 빈(class, method)을 일단 heap에 등록 해놓고(다 띄워 놓고) 사용하는 방식이기 때문에 생성자(Constructor:컨스트럭터)를 태울 수가 없다.

왜냐하면 컨스트럭터는 new 명령이 실행 될 때 실행 되는데 스프링은 new를 아얘 못쓰게 하지는 않지만 안쓰고 하는 것을 권장 한다. 그래서 컨스트럭터를 쓸수가 없지만 경우에 따라서 빈이 뜰 때 실행을 하고 싶은 코드가 있다.

그럴때 @PostConstructor라는 애노테이션을 쓴다.

예제는 아래와 같다.

import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;

@Service
public class VotingService {

    @PostConstruct
    private void postConstructor() {
        System.out.println("---- hello ----");
    }
}

설명을 붙여보자면 @Service라고 이름 붙인 서비스가 스프링 애플리케이션 컨텍스트(ApplicationContext)에 등록 될 때 "----hello----"가 출력 되도록 하는 예제이다.

이렇게 해놓고 스프링 부트를 띄우면 콘솔에 아래와 같은 결과가 나온다.

2018-06-04 10:45:09.874  INFO 16666 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2018-06-04 10:45:09.908  INFO 16666 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2018-06-04 10:45:11.831  INFO 16666 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
---- hello ----
2018-06-04 10:45:12.624  INFO 16666 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-06-04 10:45:12.786  INFO 16666 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6025e1b6: startup date [Mon Jun 04 10:45:03 KST 2018]; root of context hierarchy
2018-06-04 10:45:12.836  WARN 16666 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning

end.

Sort:  

Congratulations @kyeongrok! You received a personal award!

Happy Birthday! - You are on the Steem blockchain for 1 year!

You can view your badges on your Steem Board and compare to others on the Steem Ranking

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Coin Marketplace

STEEM 0.13
TRX 0.22
JST 0.030
BTC 81583.53
ETH 1861.55
USDT 1.00
SBD 0.81