首页 > 解决方案 > Spring全套初始化方法及其标准顺序。@PostConstruct

问题描述

在春季的BeanFactory 文档中,他们订购了 1. 到 14. 分。

但是你会在哪里订购 @PostContruct 呢?

标签: javaspringapplicationcontextpostconstruct

解决方案


尽管在 java 文档中没有明确提及,但似乎 @PostConstruct 确实出现在 BeanPostProcessors 的 postProcessBeforeInitialization 方法之前或具有相同的顺序。它肯定出现在 ServletContextAware 的 setServletContext 之后和 InitializingBean 的 afterPropertiesSet 之前。所以你可以假设它是 11 的顺序。

我运行了以下代码和以下日志:

MyBean instance created
Calling post construct
Called postProcessAfterInitialization() for :myBean
13:00:26.269 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@17695df3, started on Thu Jun 25 13:00:26 IST 2020
public class MyApplication {

    public static void main(String[] args) {

        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.register(MyConfiguration.class);
        ctx.getBeanFactory().addBeanPostProcessor(new CustomBeanPostProcessor());
        ctx.refresh();


        ctx.close();
    }
public class MyBean {

  public MyBean() {
    System.out.println("MyBean instance created");
  }

  @PostConstruct
  private void init() {
    System.out.println("Calling post construct");
  }

}
public class MyConfiguration {
  @Bean
  @Scope(value="singleton")
  public MyBean myBean() {
    return new MyBean();
  }

}

推荐阅读