You can use several methods to Execute something after a Spring Bean is Initialized but the most popular one is the @PostConstruct
annotation.
Here’s an example:
import org.springframework.stereotype.Component;
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("My bean is initialized");
// Your code here
}
}
In this example, The Spring Engine will execute the init()
after Spring has finished configuring the bean and all fields are Initialized.
Note that this annotation is part of the Java EE standard, but Spring also supports it. This means you can use @PostConstruct
in your Spring application just like you would in a Java EE environment.
Also, keep in mind that the order of initialization is not guaranteed. If you have multiple beans with @PostConstruct
methods, the order in which they are called is not defined.
If you need to execute code after all beans have been initialized, you can use the @PostLoad
annotation (if available) or implement a custom bean post processor.
Here’s an example of how to create a custom bean post processor:
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
public class MyBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println("Bean " + beanName + " is initialized");
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
}
Then you need to register this post processor in your Spring application context:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
@Bean
public MyBeanPostProcessor myBeanPostProcessor() {
return new MyBeanPostProcessor();
}
}
In this example, the postProcessAfterInitialization
method will be called after each bean is initialized.
For more Spring articles, check out https://programtom.com/dev/category/software-development/spring/