Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Spring Bean Lifecycle Management

Tech May 9 3

Bean Initialization Timeline

  1. Instantiate the bean via constructor or factory method
  2. Populate bean properties through dependency injection
  3. If bean implements BeanNameAware, invoke setBeanName()
  4. If bean implements BeanFactoryAware, invoke setBeanFactory()
  5. If bean implements ApplicationContextAware, invoke setApplicationContext()
  6. Execute BeanPostProcessor.postProcessBeforeInitialization() for all configured processors
  7. If bean implements InitializingBean, invoke afterPropertiesSet()
  8. Execute custom initialization method specified via init-method
  9. Execute BeanPostProcessor.postProcessAfterInitialization() for all configured processors
  10. Bean becomes ready for use
  11. Container shutdown initiated
  12. If bean implements DisposableBean, invoke destroy()
  13. Execute custom destruction method specified via destroy-method

Initialization Method Execution Order

InstantiationAwareBeanPostProcessor → BeanPostProcessor (pre-initialization) → @PostConstruct → InitializingBean.afterPropertiesSet() → Custom init-method

Key Component Responsibilities

DeferredImportSelector: Extends bean registration capabilities by adding fully qualified bean names

AbstractAutowireCapableBeanFactory: Handles property injection for beans

AutowiredAnnotationBeanPostProcessor: Processes @Autowired and @Value annotations

AbstractBeanFactory.resolveEmbeddedValue(): Resolves embedded values in configuration

Complete Registration Process

BeanDefinitionRegistryPostProcessor enables custom bean definition registration through BeanDefinitionRegistry

ImportBeanDefinitionRegistrar works with @Import annotation to register additional beans programmatically

import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

public class LoggerRegistrar implements ImportBeanDefinitionRegistrar {
    @Override
    public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) {
        BeanDefinition loggerDefinition = new GenericBeanDefinition();
        loggerDefinition.setBeanClassName("com.example.ApplicationLogger");
        registry.registerBeanDefinition("appLogger", loggerDefinition);
    }
}

Configuration class implementation:

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration
@Import(LoggerRegistrar.class)
public class ApplicationConfiguration {
    // Additional configuration elements
}

Extension Points

InstantiationAwareBeanPostProcessor extends BeanPostProcessor with pre-instantiation capabilities for creating proxy objects:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

@Component
public class ProxyCreationProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> targetClass, String beanId) throws BeansException {
        if (targetClass.isAnnotationPresent(Transactional.class)) {
            return generateProxyInstance(targetClass);
        }
        return null;
    }
}

BeanPostProcessor methods handle pre and post initialization logic for bean wrapping and processing

InitializingBean.afterPropertiesSet() executes after all properties are set, suitable for resource initializtaion like thread pools

DisposableBean.destroy() handles cleanup operations during bean destruction, such as connection pool termination

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.