What happens to a Spring bean from creation to termination? 👉
Bean Definition → Metadata registered when @ ComponentScan finds @ Component, @ Service, @ Repository classes. Or when @ Bean method parsed in @ Configuration classes. BeanDefinition contains: class name, scope (singleton/prototype), dependencies, factory method, init/destroy method names.
Constructor Invocation → Spring uses reflection to instantiate via constructor. For @ Component class with no explicit constructor, default no-arg constructor called. For @ Bean methods, method called to create instance. If multiple constructors, @ Autowired marks which to use.
Dependency Injection → Spring resolves constructor parameters via @ Autowired, injects matching beans. For setter injection (@ Autowired on setter), setter called after construction. For field injection (@ Autowired on field), reflection used to set field directly. Autowire by type, then qualifier, then name.
BeanNameAware Interface → If bean implements BeanNameAware, setBeanName(String name) called with bean's registration name. Allows bean to know its own name in container.
BeanFactoryAware Interface → If bean implements BeanFactoryAware, setBeanFactory(BeanFactory factory) called. Bean can query factory for other beans if needed.
BeanClassLoaderAware Interface → If bean implements BeanClassLoaderAware, setBeanClassLoader(ClassLoader classLoader) called. Provides classloader context.
InitializingBean Interface → If bean implements InitializingBean, afterPropertiesSet() called after all properties set and aware callbacks done. Allows custom initialization logic like opening connections.
@ PostConstruct Method → If method annotated with @ PostConstruct, it's called after construction and dependency injection complete. Runs before bean is available to others. Can only have one, no parameters except @ Inject optional.
BeanPostProcessor.postProcessAfterInitialization() → Custom BeanPostProcessor implementations can wrap or modify bean. Runs after all initialization. Used for proxying (AOP), validation, dynamic bean enhancement.
Bean Ready → Bean now available in ApplicationContext. Can be injected into other beans. Singleton beans exist for lifetime of context. Prototype beans used and discarded per request.
@ PreDestroy Method → When context shuts down, @ PreDestroy method called on beans. Allows cleanup: close database connections, stop timers, release resources. Runs in reverse order of creation.
DisposableBean Interface → If bean implements DisposableBean, destroy() method called on shutdown. Alternative to @ PreDestroy. Both called if present; order depends on implementation."