简体   繁体   English

Spring全套初始化方法及其标准顺序。 @PostConstruct

[英]Spring full set of initialization methods and their standard order. @PostConstruct

in the BeanFactory documentation from spring they ordered 1. to 14. points.在 spring 的BeanFactory 文档中,他们订购了 1 到 14 分。

But where you would order @PostContruct into it?但是你会在哪里订购 @PostContruct 呢?

It runs just before afterPropertiesSet .它在afterPropertiesSet之前运行。

Although it is not clearly mentioned in the java doc, it seems that @PostConstruct does come before or has same order postProcessBeforeInitialization methods of BeanPostProcessors.尽管在 java 文档中没有明确提及,但似乎 @PostConstruct 确实出现在 BeanPostProcessors 的 postProcessBeforeInitialization 方法之前或具有相同的顺序。 And it definitely comes after ServletContextAware's setServletContext and before InitializingBean's afterPropertiesSet.它肯定出现在 ServletContextAware 的 setServletContext 之后和 InitializingBean 的 afterPropertiesSet 之前。 So you can assume it order of 11.所以你可以假设它是 11 的顺序。

I ran the following code and the following logs:我运行了以下代码和以下日志:

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();
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM