Spring Life Cycle
Spring Life Cycle
@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws
BeansException {
System.out.println("postProcessBeforeInitialization: " + beanName + " avant initialisation");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws
BeansException {
System.out.println("postProcessAfterInitialization: " + beanName + " après initialisation");
return bean;
}
}
And for each Bean definition we can Implement two interfaces : DisposableBean, InitializingBean
The InitializingBean interface is a part of the Spring Framework's lifecycle management and is used
to define initialization logic for a bean. It provides a callback method, afterPropertiesSet(), which is
invoked by the Spring container after the bean's properties have been set and dependency
injection is complete.
@Component
public class MailNotificationService implements NotificationService, DisposableBean,
InitializingBean {
@PostConstruct
public void init() {
System.out.println("MailNotificationService initialisé.");
}
@PreDestroy
public void preDestroyMethod() {
System.out.println("MailNotificationService va être détruit.");
}
@Override
public void destroy() throws Exception {
System.out.println("MailNotificationService destroy() appelé.");
}
@Override
public void sendNotification(String message) {
System.out.println("Sending mail regarding " + message);
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet : Méthode exécutée après @PostConstruct.");
}
}
And we create a main program that permits to an external user to intervene with our application
after initialization and injection, and after getting ready to use:
if ("CLOSEIT".equalsIgnoreCase(userInput.trim())) {
System.out.println("Fermeture de l'application...");
break;
}
if ("1".equals(userInput.trim())) {
System.out.print("Entrez l'identifiant du véhicule : ");
String vehicleId = scanner.nextLine();
The lifecycle of a bean in Spring involves multiple stages, each executed in a specific order to ensure
proper initialization and destruction. Here's an explanation of the lifecycle and how the provided
code demonstrates it:
1. Bean Instantiation
Spring starts by instantiating the bean using its constructor or a factory method.
2. Dependency Injection
Spring injects the required dependencies into the bean via @Autowired, setters, or
constructor arguments.
4. Initialization Callbacks
Spring provides several ways to execute custom logic during the initialization phase, in the following
order:
1. @PostConstruct:
o A method annotated with @PostConstruct is called after dependency injection.
o It is often used for initial setup that requires injected dependencies.
Example Output:
MailNotificationService initialisé.
RouteCoastService initialisé.
2. InitializingBean Interface (afterPropertiesSet Method):
o This method is called after @PostConstruct.
o It is used for initialization logic that needs to run after all properties are set.
Example Output:
5. Bean Usage
The bean is now fully initialized and ready for use by the application.
@Component
public class CustomBeanPostProcessorFactory implements BeanPostProcessorFactory {
@Override
public BeanPostProcessor createBeanPostProcessor() {
return new CustomBeanPostProcessor();
}
}
3. Register the BeanPostProcessor Dynamically: Use the factory in your application
configuration to register BeanPostProcessor instances.
@Configuration
public class BeanPostProcessorConfig {
@Bean
public BeanPostProcessor customBeanPostProcessor(BeanPostProcessorFactory factory) {
return factory.createBeanPostProcessor();
}
}
Example Usage
The CustomBeanPostProcessor implementation from your code will be created and registered
using the factory.
Spring will use this BeanPostProcessor during the initialization of beans.
When to Use a BeanPostProcessorFactory
Dynamic Creation: If your application needs to dynamically decide the behavior or type of
BeanPostProcessor based on external factors like configuration or runtime conditions.
Centralized Management: To ensure all BeanPostProcessor instances are created and
managed consistently.