Wywołania zwrotne cyklu życia
Podepnij się do faz inicjalizacji i niszczenia beana
Wywołania zwrotne cyklu życia to bezpłatna lekcja Spring Boot 4 Microservices & REST APIs na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Spring Boot 4 Microservices & REST APIs, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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
Często zadawane pytania
Czy lekcja „Wywołania zwrotne cyklu życia” jest bezpłatna?
Tak — pełny tekst „Wywołania zwrotne cyklu życia” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Spring Boot 4 Microservices & REST APIs, przejdź na CoddyKit PRO. Kurs Spring Boot 4 Microservices & REST APIs zawiera 4 lekcji w sumie.
Co nauczysz się w „Wywołania zwrotne cyklu życia”?
Podepnij się do faz inicjalizacji i niszczenia beana Ćwiczysz Spring Boot 4 Microservices & REST APIs z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Spring Boot 4 Microservices & REST APIs?
Nie wymagamy żadnego doświadczenia. Spring Boot 4 Microservices & REST APIs w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Wywołania zwrotne cyklu życia”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Spring Boot 4 Microservices & REST APIs?
Tak. Każda lekcja Spring Boot 4 Microservices & REST APIs zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Kontener IoC Spring
- Wstrzykiwanie przez konstruktor a przez pole
- Zakresy beanów
- Wywołania zwrotne cyklu życia