Scope dei bean e gestione del ciclo di vita
Impari come Spring crea, assegna lo scope e distrugge i bean e come collegarsi al loro ciclo di vita con callback.
Scope dei bean e gestione del ciclo di vita è una lezione Spring Boot 4 Complete Guide gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Complete Guide, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Complete Guide include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Domande Frequenti
La lezione «Scope dei bean e gestione del ciclo di vita» è gratuita?
Sì — il testo completo di «Scope dei bean e gestione del ciclo di vita» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Complete Guide, passa a CoddyKit PRO. Il corso Spring Boot 4 Complete Guide include 4 lezioni in totale.
Cosa imparerò in «Scope dei bean e gestione del ciclo di vita»?
Impari come Spring crea, assegna lo scope e distrugge i bean e come collegarsi al loro ciclo di vita con callback. Eserciti Spring Boot 4 Complete Guide con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Spring Boot 4 Complete Guide?
Non è richiesta alcuna esperienza precedente. Spring Boot 4 Complete Guide su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Scope dei bean e gestione del ciclo di vita»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Complete Guide?
Sì. Ogni lezione Spring Boot 4 Complete Guide include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Comprendere il contenitore IoC di Spring
- Dependency injection nella pratica
- Esternalizzare le proprietà dell’applicazione
- Scope dei bean e gestione del ciclo di vita