0Pricing
Spring Boot 4 Microservices & REST APIs · 课时

生命周期回调

接入 Bean 的初始化和销毁阶段

生命周期回调 是 CoddyKit 上的免费 Spring Boot 4 Microservices & REST APIs 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Spring Boot 4 Microservices & REST APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Spring Boot 4 Microservices & REST APIs 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

The Bean Lifecycle

Beyond construction, beans pass through phases: the container instantiates them, injects dependencies, runs initialization callbacks, serves requests, then runs destruction callbacks at shutdown.

Hooking into these phases lets you set up and clean up resources reliably.

Why Not Use the Constructor?

A constructor runs before dependencies are injected when using setter/field injection, so collaborators may still be null. Initialization that depends on injected beans belongs in a post-construction callback, not the constructor.

With constructor injection the dependencies are present, but lifecycle callbacks still give a clear, intent-revealing place for setup.

@PostConstruct

A method annotated @PostConstruct runs once after the bean is fully constructed and all dependencies are injected. Use it for warm-up tasks like priming a cache or validating state.

@Service
public class CatalogService {
    private final ProductRepository repo;
    private List<Product> cache;
    public CatalogService(ProductRepository repo) { this.repo = repo; }

    @PostConstruct
    void warmUp() {
        this.cache = repo.findAllActive();
    }
}

@PreDestroy

A method annotated @PreDestroy runs once when the context is shutting down, before the bean is destroyed. Use it to release resources like connections, thread pools, or file handles.

@Service
public class ConnectionManager {
    private final ExecutorService pool = Executors.newFixedThreadPool(4);

    @PreDestroy
    void shutdown() {
        pool.shutdown();
    }
}

The InitializingBean Interface

Implementing InitializingBean provides afterPropertiesSet, called after dependencies are set. It works but couples your class to Spring’s API, so annotations are usually preferred.

@Service
public class IndexService implements InitializingBean {
    @Override
    public void afterPropertiesSet() {
        buildIndex();
    }
}

The DisposableBean Interface

Symmetrically, DisposableBean supplies a destroy method for cleanup. Like InitializingBean, it ties you to Spring interfaces.

@Service
public class IndexService implements DisposableBean {
    @Override
    public void destroy() {
        releaseIndex();
    }
}

@Bean initMethod and destroyMethod

For beans you create with @Bean (often third-party types), specify lifecycle methods by name. This keeps the external class free of Spring annotations.

@Bean(initMethod = "start", destroyMethod = "stop")
public CacheClient cacheClient() {
    return new CacheClient(config);
}

Ordering of Callbacks

When several mechanisms are present, the init order is: @PostConstruct first, then InitializingBean.afterPropertiesSet, then a custom initMethod. Destruction mirrors this with @PreDestroy first.

Preferred Approach

For modern code, prefer the JSR-250 annotations @PostConstruct and @PreDestroy. They are concise, framework-neutral, and clearly express intent without coupling to Spring interfaces.

A Caveat on Prototype Destruction

The container does not call destruction callbacks for prototype beans — it hands them off and forgets them. If a prototype holds resources, you are responsible for releasing them yourself.

Graceful Shutdown

Spring Boot triggers destruction callbacks during a clean shutdown (for example on SIGTERM). Combined with graceful shutdown settings, this lets in-flight work finish and resources close cleanly before exit.

server:
  shutdown: graceful
spring:
  lifecycle:
    timeout-per-shutdown-phase: 20s

Quick Check

Test your understanding of lifecycle callbacks.

Recap

Lifecycle callbacks manage setup and cleanup.

  • @PostConstruct runs after dependencies are injected
  • @PreDestroy runs before shutdown for cleanup
  • InitializingBean/DisposableBean work but couple to Spring
  • Use initMethod/destroyMethod for @Bean-created types
  • Prototype destruction is your responsibility

常见问题解答

「生命周期回调」课时是免费的吗?

是的 — 「生命周期回调」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Spring Boot 4 Microservices & REST APIs 课程的其余内容,请升级到 CoddyKit PRO。 Spring Boot 4 Microservices & REST APIs 课程共包含 4 节课。

「生命周期回调」这节课中我会学到什么?

接入 Bean 的初始化和销毁阶段 你通过在浏览器中直接运行的动手代码来练习 Spring Boot 4 Microservices & REST APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Spring Boot 4 Microservices & REST APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Spring Boot 4 Microservices & REST APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「生命周期回调」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Spring Boot 4 Microservices & REST APIs 课中编写并运行代码吗?

能。每节 Spring Boot 4 Microservices & REST APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Spring IoC 容器
  2. 构造函数注入与字段注入
  3. Bean 作用域
  4. 生命周期回调
← 返回 Spring Boot 4 Microservices & REST APIs