@PostConstruct annotation and spring lifecycle

后端 未结 2 2057
抹茶落季
抹茶落季 2020-12-29 04:47

I\'m new to Spring, I would like to know:

I have a java class annotated with @Component (spring) and inside I have a method annotated with @PostC

相关标签:
2条回答
  • 2020-12-29 05:08

    The handling of annotations such as @PostConstruct, @Resource, @PreDestroy is done via a BeanPostProcessor, in this case the CommonAnnotationBeanPostProcessor. You can see in the following diagram from Spring that these BPP's are handled after Dependency Injection but before Bean Ready For Use (Which means as much as injectable).

    0 讨论(0)
  • 2020-12-29 05:26

    If you are asking is injection of given class happening after @PostConstruct in that bean is called, then the answer is yes - @PostConstruct is executed before bean is considered as "injectable"

    If you are asking if @PostConstruct on given bean is executed after all injections has been done (on the same bean) - then yes - @PostConstruct is executed after injections are commited to given bean. This is the reason it exists. Normally you could put @PostConstruct actions into the constructor. However, when new object is created (constructor is called) injections are not performed yet - so any initialization that depends on injected objects would fail due to NPE. That is why you need @PostConstruct

    0 讨论(0)
提交回复
热议问题