目录
1.Bean 的6种作用域
Spring 容器在初始化一个 Bean 的实例时, 同时会指定该实例的作用域. Spring 有6种作用域, 最后4种是基于 Spring MVC 生效的:
- singleton: 单例作用域
- prototype: 原型作用域(多例作用域)
- request: 请求作用域
- session: 会话作用域
- application: 全局作用域
- webSocket: HTTP WebSocket 作用域
2.说明
在这里只介绍前四种, application 和 webSocket 就不在这里介绍了.
2.1 singleton:
首先官方给出的说明是: (Default) Scopes a single bean definition to a single object instance for each Spring IoC container. 大概的意思就是说单例作用域下的 Bean 在 IoC 容器中只存在一个实例, 获取Bean(即通过 applicationContext.getBean 等方法获取)及装配 Bean(即通过@Autowired注入)都是同⼀个对象. 通常无状态的 Bean 使用该作用域(无状态表示 Bean 对象的属性不需要更新, 换句话说就是所有人只调用不修改). 还有一点需要注意的是 Spring 默认选择该作用域.
@Controller
public class UserController2 {
@Autowired
private User user;
public void doMethod() {
User user1 = user;
System.out.println("userController2 修改前 ->" + user);
user1.setName("皮卡丘");
System.out.println("userController2 修改后 ->" + user);
}
}
@Controller
public class UserController3 {
@Autowired
private User user;
public void doMethod() {
System.out.println("userController3 ->" + user);
}
}
优点:效率高,因为对象只加载一次
缺点:线程不安全,解决办法就是使用 ThreadLocal(本地线程变量)
2.2 prototype:
这个原型模式又叫做多例模式, 和单例模式相对应. 官方给出就得我说明是: Scopes a single bean definition to any number of object instances. 大概意思是每次对该作⽤域下的 Bean 的请求都会创建新的实例: 获取Bean(即通过 applicationContext.getBean 等方法获取)及装配 Bean(即通过@Autowired注入)都是新的对象实例. 通常有状态的 Bean 使用该作用域.
2.3 request:
官方给出的说明是: Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. 大概意思就是每次 http 请求会创建新的Bean实例,类似于prototype. 限定 SpringMVC (Spring Web)中使用.
2.4 session:
官方给出的说明是: Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. 意思就是在⼀个 http session 中,定义⼀个Bean实例, 类似于多线程的 ThreadLocal, 应用场景为用户会话的共享 Bean, 比如: 记录一个用户的登录信息. 也是限定 SpringMVC 中使用. 一个 http 会话共享一个 Bean
2.5 单例作用域(singleton) VS 全局作用域(application)
- singleton 是 Spring Core 的作用域; application 是 Spring Web 中的作用域;
- singleton 作用于 IoC 容器, 而 application 作用于 Servlet 容器.
3.设置作用域
使用 @Scope 标签就可以用来声明 Bean 的作用域, 比如设置 Bean 的作用域, 如下代码所示:
public class Users {
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Bean
public User user1() {
User user = new User();
user.setId(1);
user.setName("Java");
return user;
}
}
@Scope 标签既可以修饰方法也可以修饰类, @Scope 有两种设置方式:
- 直接设置值: @Scope(“prototype”)
- 使用全局变量设置: @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
4. Bean 的生命周期
4.1 过程
笼统地讲:
所谓的生命周期就是指一个对象从诞生到销毁的整个生命过程. Bean 的生命周期从大的方向可以分为以下5个部分:
- 实例化 Bean(为 Bean分配内存空间), 对应类在 JVM 中的 “加载过程”, 这是一个从无到有的过程, 将字节码转换成内存中的对象, 只分配了内存
- 设置 Bean 属性(Bean 注入和装配)
- Bean 初始化
执行各种通知 =》初始化的前置方法=》初始化方法=》初始化的后置方法
3.1 实现了各种 Aware 通知的⽅法,如 BeanNameAware、BeanFactoryAware、ApplicationContextAware 的接口方法;
3.2 执行 BeanPostProcessor 初始化前置方法;
3.3 执行 @PostConstruct 初始化方法,依赖注入操作之后被执行;
3.4 执行自己指定的 init-method 方法(如果有指定的话);
3.5 执行 BeanPostProcessor 初始化后置方法 - 使用 Bean
- 销毁 Bean
以上五步可以这样形象的来理解:
- 买了一套毛坯房
- 购买装修材料
- 房子装修
a: 各种通知: 打电话给各个装修师傅来施工
b: 前置工作, 师傅到达现场, 勘察环境, 制定装修方案
c: 开始装修: 两类师傅进行装修, 技术好的, 技术一般的
d: 装修完毕后, 进行清理工作 - 入住
- 不用这个房子了, 卖掉
4.2 代码演示
// 使用 xml 的方式注入
public class BeanLifeComponent implements BeanNameAware {
@Override
public void setBeanName(String s) {
System.out.println("执行了通知");
}
@PostConstruct
public void pstConstruct(){
System.out.println("执行了 @PostConstruct");
}
public void init(){
System.out.println("执行了 init-method 方法");
}
@PreDestroy
public void preDestroy(){
System.out.println("执行销毁方法");
}
}
// xml
<?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">
<content:component-scan base-package="com.demo"></content:component-scan>
<bean id="myComponent" class="com.demo.component.BeanLifeComponent" init-method="init"></bean>
</beans>
// 执行代码及效果
public class APP2 {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring_config.xml");
BeanLifeComponent myComponent = applicationContext.getBean("myComponent", BeanLifeComponent.class);
System.out.println("使用 Bean");
// 销毁 Bean
applicationContext.destroy();
}
}
4.3 是否真的是先设置属性, 再初始化
假设有三个类: A类 B类 C类, A 中注入并调用了 B, B 中注入并调用了 C(A B C都存进 Spring 中了), 在 main 中调用 A 的方法, 看看 @PostConstruct 得出执行顺序是否是先 C 再 B 最后 A, 如果是, 则证明确实是先设置属性, 再初始化, 代码实现如下:
@Component
public class AComponent {
@Autowired
private BComponent bComponent;
@PostConstruct
public void postConstruct(){
System.out.println("执行了 A 的 PostConstruct");
}
}
@Component
public class BComponent {
@Autowired
private CComponent component;
@PostConstruct
public void postConstruct(){
System.out.println("执行了 B 的 PostConstruct");
}
}
@Component
public class CComponent {
@PostConstruct
public void postConstruct(){
System.out.println("执行了 C 的 PostConstruct");
}
}
public class App3 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring_config.xml");
AComponent aComponent = context.getBean("AComponent", AComponent.class);
}
}
执行结果:
5. Spring 的生命周期
- 启动容器
- 读取配置进行 Bean 的实例化
- 将 Bean 加载到容器中
- 看看有没有 DI 之类的操作,有的话就装配Bean属性(给 DI 操作赋值)
- Spring 执行相关的业务代码
- 销毁释放 Bean
- 关闭 Spring