1

I've tried to create a Spring bean and log all possible stages of his lifecycle.

But I've noticed that in this case a method annotated with @PostConstruct isn't invoked.

I suppose it happens because BeanFactoryPostProcessor and ApplicationContextAware force container to instantiate it as early as possible, but I don't know exactly.

Could you explain me, please?

Please consider a code snippet below:

public class F implements BeanFactoryPostProcessor, ApplicationContextAware {

        @PostConstruct
        private void postConstruct() {
            System.out.println("Hi from postContruct()");
        }

        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            System.out.println("Hi from setApplicationContext()");
        }

        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            System.out.println("Hi from postProcessBeanFactory()");
        }
}

And the output is:

Hi from setApplicationContext()
Hi from postProcessBeanFactory()
Pasha
  • 1,768
  • 6
  • 22
  • 43
  • 1
    I think we need to see how you're configuring your Spring application (if XML, the context.xml file, else the annotations on the Configuration or SpringBootApplication class. As it is, my guess would be you did not enable annotations, so Spring doesn't know to look for that PostConstruct annotation... – moilejter Aug 18 '18 at 01:44
  • Spring recognizes PostConstruct annotion out of the box. The problem is that for some reason, they are not invoked on BeanFactoryPostProcessors. Implementing DisposableBean or setting initMethod still works though. Declaring the bean as Component for component scan or explicitly in xml or Java config doesn't make any difference. – Nima Ajdari Aug 18 '18 at 08:56
  • @NimaAJ hi, how do you think what can be the reason? – Pasha Aug 18 '18 at 09:38
  • @moilejter it doesn’t matter. In my case Java Config and get bran from context in psvm(). What do you mean by enable annotations? They are working by default – Pasha Aug 18 '18 at 09:40
  • The reason is that `@PostConstruct` is evaluated for beans, and a `BeanFactoryPostProcessor` isn't one of you don't declare it as such (ie add a`@Component` annotation to the class). – daniu Jun 22 '20 at 20:24

1 Answers1

0

Try implementing org.springframework.beans.factory.InitializingBean instead of using @PostConstruct annotation. BeanFactoryPostProcessor may be one peculiar case which happens early enough in the lifecycle so that the lifecycle annotations don't function yet.

I know I had the same issue with @PreDestroy on my BeanFactoryPostProcessor configuration class. Using org.springframework.beans.factory.DisposableBean solved it.

Pawel Zieminski
  • 439
  • 3
  • 8