You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 MyBean configuration 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:

  1. Autowired Injection (Step 1): Spring injects the MyBean instance (note this is a circular dependency, which Spring handles via CGLIB proxies for @Configuration classes).
  2. @PostConstruct (Step3): After the MyBean configuration bean is fully instantiated and dependencies are injected, the testPostConsturctMethod runs.
  3. @Bean Method (Step2): The testMethod is executed when Spring creates the bean it defines. Since this bean isn’t a dependency of MyBean, this happens after the MyBean configuration bean’s lifecycle is complete.

Question 2: @Bean in Parent Class

The execution order does not change. Here’s why:

  • The parent class MySuperClass isn’t a separate Spring bean—only MyBean (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 MyBean still proceeds as: instantiate → inject dependencies (Step1) → call @PostConstruct (Step3). The @Bean method from the parent (Step2) runs when its bean is created, which is after MyBean’s @PostConstruct (unless that bean is a dependency of MyBean).
  • There’s no "separate parent lifecycle"—all parent class methods are part of the MyBean bean’s implementation.

内容的提问来源于stack exchange,提问作者Kaepxer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 01:12:40