Bean的生命周期分为五大部分
1.实例化Bean,为Bean分配空间
2.Bean的装配和注入
3.Bean的初始化
- 实现Aware通知的方法,如ApplicationContextAware等
- 执行BeanProcessor初始化前置方法
- 执行PostConstruct方法
- 执行自己指定的init-method 方法
- 执行BeanProcessor初始化后置方法
4.使用Bean
5.销毁Bean
销毁容器的各种⽅法,如 @PreDestroy方法等
实例代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:content="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置存储 Bean 对象的扫描根路径-->
<content:component-scan base-package="com.rhaegal"></content:component-scan>
<!--注入beanlife对象到Spring容器中-->
<bean name = "beanlife" class="com.rhaegal.controler.BeanLifeComponent" init-method="initMethod"></bean>
</beans>
public class BeanLifeComponent implements BeanNameAware {
@Override
public void setBeanName(String s) {
System.out.println("执行了 BeanName 通知:" + s);
}
//这里的方法名任意
public void initMethod(){
System.out.println("执行了 initMethod 方法");
}
//这里的方法名任意
@PostConstruct
public void myPostConstruct(){
System.out.println("执行了 PostConstruct 方法");
}
//这里的方法名任意
@PreDestroy
public void myPreDestroy(){
System.out.println("执行力 PreDestroy 方法");
}
public void use(){
System.out.println("执行了 use 方法");
}
}
public class App {
public static void main(String[] args) {
//Bean的生命周期
ClassPathXmlApplicationContext context =
new ClassPathXmlApplicationContext("spring-config.xml");
BeanLifeComponent component =
context.getBean("beanlife",BeanLifeComponent.class);
component.use();
//关闭容器
context.destroy();
}
}
执行结果如下: