Обратные вызовы жизненного цикла
Подключайтесь к этапам инициализации и уничтожения бина
«Обратные вызовы жизненного цикла» — бесплатный урок Spring Boot 4 Microservices & REST APIs на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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: 20sQuick Check
Test your understanding of lifecycle callbacks.
Recap
Lifecycle callbacks manage setup and cleanup.
@PostConstructruns after dependencies are injected@PreDestroyruns before shutdown for cleanupInitializingBean/DisposableBeanwork but couple to Spring- Use
initMethod/destroyMethodfor@Bean-created types - Prototype destruction is your responsibility
Часто задаваемые вопросы
Урок «Обратные вызовы жизненного цикла» бесплатный?
Да — полный текст урока «Обратные вызовы жизненного цикла» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Microservices & REST APIs, подпишись на CoddyKit PRO. Курс Spring Boot 4 Microservices & REST APIs содержит 4 уроков всего.
Чему я научусь в уроке «Обратные вызовы жизненного цикла»?
Подключайтесь к этапам инициализации и уничтожения бина Ты практикуешь Spring Boot 4 Microservices & REST APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Boot 4 Microservices & REST APIs?
Предыдущий опыт не требуется. Spring Boot 4 Microservices & REST APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Обратные вызовы жизненного цикла»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Boot 4 Microservices & REST APIs?
Да. Каждый урок Spring Boot 4 Microservices & REST APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Контейнер Spring IoC
- Внедрение через конструктор и поле
- Области видимости бинов
- Обратные вызовы жизненного цикла