Области действия компонентов и управление жизненным циклом
Узнайте, как Spring создаёт, ограничивает область действия и уничтожает компоненты, а также как подключаться к их жизненному циклу с помощью обратных вызовов.
«Области действия компонентов и управление жизненным циклом» — бесплатный урок Spring Boot 4 Complete Guide на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Spring Boot 4 Complete Guide, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Spring Boot 4 Complete Guide содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What Is a Bean Scope?
A scope defines how many instances of a bean Spring creates and how long they live. The default scope is singleton: one shared instance per container.
Singleton Scope
With singleton, every injection point receives the same object. This is ideal for stateless services and is the most common choice.
@Service
public class PricingService {
// one shared instance across the app
}Prototype Scope
The prototype scope creates a new instance every time the bean is requested. Use it for stateful or short-lived objects.
@Component
@Scope("prototype")
public class ReportBuilder {
}Web-Aware Scopes
In web apps you also have request and session scopes, tying a bean's lifetime to a single HTTP request or a user session respectively.
- request — one per HTTP request
- session — one per user session
Choosing the Right Scope
Default to singleton for stateless logic. Reach for other scopes only when a bean must hold per-request or per-instance state, since wider sharing of mutable state causes bugs.
The Bean Lifecycle
Spring instantiates a bean, injects its dependencies, runs initialization callbacks, serves it during the app's life, and finally runs destruction callbacks on shutdown.
Initialization with @PostConstruct
Annotate a method with @PostConstruct to run setup logic after dependencies are injected, such as opening a connection or warming a cache.
@PostConstruct
public void init() {
System.out.println("Bean is ready");
}Cleanup with @PreDestroy
A @PreDestroy method runs just before the bean is removed, letting you release resources cleanly.
@PreDestroy
public void cleanup() {
System.out.println("Releasing resources");
}Lazy Initialization
By default singletons are created at startup. Marking a bean @Lazy defers creation until it is first needed, which can speed up boot time for rarely used beans.
@Lazy
@Service
public class HeavyService {
}Prototype Beans and Destruction
Be aware that Spring does not manage the full destruction lifecycle of prototype beans. The container hands them off and forgets them, so you must release their resources yourself.
Putting It Together
A typical singleton service uses @PostConstruct to initialize and @PreDestroy to clean up, giving you precise control over startup and shutdown behavior.
@Service
public class CacheService {
@PostConstruct void load() {}
@PreDestroy void flush() {}
}Quick Check
Test your understanding of bean scopes and lifecycle.
Recap
You learned the singleton, prototype, request, and session scopes, the bean lifecycle, and how to hook into it with @PostConstruct, @PreDestroy, and @Lazy.
Часто задаваемые вопросы
Урок «Области действия компонентов и управление жизненным циклом» бесплатный?
Да — полный текст урока «Области действия компонентов и управление жизненным циклом» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Spring Boot 4 Complete Guide, подпишись на CoddyKit PRO. Курс Spring Boot 4 Complete Guide содержит 4 уроков всего.
Чему я научусь в уроке «Области действия компонентов и управление жизненным циклом»?
Узнайте, как Spring создаёт, ограничивает область действия и уничтожает компоненты, а также как подключаться к их жизненному циклу с помощью обратных вызовов. Ты практикуешь Spring Boot 4 Complete Guide с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Spring Boot 4 Complete Guide?
Предыдущий опыт не требуется. Spring Boot 4 Complete Guide на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Области действия компонентов и управление жизненным циклом»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Spring Boot 4 Complete Guide?
Да. Каждый урок Spring Boot 4 Complete Guide включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Знакомство с контейнером Spring IoC
- Внедрение зависимостей на практике
- Внешняя конфигурация свойств приложения
- Области действия компонентов и управление жизненным циклом