Spring中Bean的生命周期
如何理解
要理解Bean的生命周期,需要先理解IOC在spring中的实现。
IoC在sping中是通过一个容器来实现的,它管理对象的生命周期和他们的依赖。当Bean在spring中被创建时,容器会做一些事情来管理它的生命周期,包含:
- 实例化(Instantiation) 容器使用构造方法或者一个工厂方法来创建一个Bean的实例。JAVA
1
2
3
4
5
6
7
8
9
10
11public class ExampleBean {
// Constructor injection
public ExampleBean(Dependency dependency) {
// ...
}
// Factory method injection
public static ExampleBean create(Dependency dependency) {
// ...
}
} - 依赖注入(Dependency Injection):容器通过构造方法或者setter注入Bean需要的依赖JAVA
1
2
3
4
5
6
7
8
9
10
11
12
13public class ExampleBean {
private Dependency dependency;
// Constructor injection
public ExampleBean(Dependency dependency) {
this.dependency = dependency;
}
// Setter injection
public void setDependency(Dependency dependency) {
this.dependency = dependency;
}
} - 初始化(Initialization) 容器调用Bean的初始化方法,例如@PostConstruct注解的方法。JAVA
1
2
3
4
5
6public class ExampleBean {
public void init() {
// ...
}
} - 使用: Bean在应用中使用
- 销毁(Destruction):应用用完Bean之后,容器调用析构方法,如@PreDestroy注解的方法。JAVA
1
2
3
4
5
6public class ExampleBean {
public void destroy() {
// ...
}
}
Bean初始化的大致4个阶段
- 实例化(instantiation)
- 属性赋值(populate)
- 初始化(initialization)
- 销毁(destruction)
涉及到的扩展点的作用
- Aware接口
通过让Bean实现Aware接口,在bean中获取响应的Spring容器资源。 - BeanPostProcessor
是Spring修改Bean提供的强大扩展点,可作用于容器中所有Bean。
- Post title:Spring中Bean的生命周期
- Post author:郭旭升
- Create time:2022-11-15 14:27:02
- Post link:https://mvpsheng.github.io/2022/11/15/Spring中Bean的生命周期/
- Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
Related Issues not found
Please contact @mvpsheng to initialize the comment