NOTE
Bean Lifecycle
1. Process 2. Usage 3. References
This is a historical learning note and may contain outdated or incomplete understanding.
1. Process
- Instantiate the Bean.
- Inject values and references into the Bean’s corresponding properties.
- Inject Spring low-level components into the Bean through Aware interfaces.
BeanPostProcessor: execute additional logic. It runs before and afterInitializingBean, and the Bean currently being created is passed in.InitializingBean: execute additional logic, but the Bean currently being created is not passed in.DisposableBean: call thedestroymethod when the Bean is destroyed.
2. Usage
There are four approaches in total.
2.1. Specify init and destroy Methods with @Bean
public class BeanCycle
{
public BeanCycle()
{
System.out.println("1. bean created");
}
public void init()
{
System.out.println("2. bean initialized");
}
public void destroy()
{
System.out.println("3. bean destroyed");
}
}
@Bean(initMethod = "init", destroyMethod = "destroy")
public BeanCycle beanCycle()
{
return new BeanCycle();
}
2.2. Implement InitializingBean and DisposableBean
@Component
@ComponentScan("com.example.context.bean")
public class BeanCycle2 implements InitializingBean, DisposableBean
{
public BeanCycle2()
{
System.out.println("bean2 created");
}
@Override
public void afterPropertiesSet() throws Exception
{
System.out.println("bean2 properties have been set");
}
@Override
public void destroy() throws Exception
{
System.out.println("bean2 destroyed");
}
}
2.3. Annotate Methods with @PostConstruct and @PreDestroy
2.4. Implement BeanPostProcessor
@Component
public class MyBeanPostProcessor implements BeanPostProcessor
{
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException
{
System.out.println("do some work before initialization");
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException
{
System.out.println("do some work after initialization");
return bean;
}
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub