Spring Bean生命周期疑问:@PostConstruct与@Bean执行顺序及继承场景
Spring Bean Lifecycle: @PostConstruct vs @Bean Execution Order
Core Concepts
First, let’s clarify the key distinctions:
- @PostConstruct: This is a lifecycle callback for the bean it’s defined on (in your examples, the
MyBeanconfiguration bean). It runs after all dependencies of that bean are injected and immediately after the bean is instantiated. - @Bean: Methods annotated with this are used to define other beans in the Spring context. When an @Bean method executes depends on when Spring needs the bean it creates:
- For singleton beans (default), this usually happens during context initialization.
- If the bean defined by @Bean is a dependency of another bean (like the configuration bean itself), it will be created earlier to satisfy that dependency.
Question 1: Execution Order in Code Example 1
Yes, the execution order is 1 → 3 → 2:
- Autowired Injection (Step 1): Spring injects the
MyBeaninstance (note this is a circular dependency, which Spring handles via CGLIB proxies for @Configuration classes). - @PostConstruct (Step3): After the
MyBeanconfiguration bean is fully instantiated and dependencies are injected, thetestPostConsturctMethodruns. - @Bean Method (Step2): The
testMethodis executed when Spring creates the bean it defines. Since this bean isn’t a dependency ofMyBean, this happens after theMyBeanconfiguration bean’s lifecycle is complete.
Question 2: @Bean in Parent Class
The execution order does not change. Here’s why:
- The parent class
MySuperClassisn’t a separate Spring bean—onlyMyBean(the subclass) is managed as a configuration bean. - The @Bean method in the parent class is treated as part of
MyBean’s configuration. - The lifecycle of
MyBeanstill proceeds as: instantiate → inject dependencies (Step1) → call @PostConstruct (Step3). The @Bean method from the parent (Step2) runs when its bean is created, which is afterMyBean’s @PostConstruct (unless that bean is a dependency ofMyBean). - There’s no "separate parent lifecycle"—all parent class methods are part of the
MyBeanbean’s implementation.
内容的提问来源于stack exchange,提问作者Kaepxer
相关产品推荐
相关产品推荐

