【 Bean 作⽤域和⽣命周期 】

引用

从前⾯的课程我们可以看出 Spring 是⽤来读取和存储 Bean,因此在 Spring 中 Bean 是最核⼼的操作资源,所以接下来我们深⼊学习⼀下 Bean 对象

一、认识 Bean的作用域

案例分析:

假设现在有⼀个公共的 Bean,提供给 A ⽤户和 B ⽤户使⽤,然⽽在使⽤的途中 A ⽤户却“悄悄”地修改了公共 Bean 的数据,导致 B ⽤户在使⽤时发⽣了预期之外的逻辑错误

我们预期的结果是,公共 Bean 可以在各⾃的类中被修改,但不能影响到其他类

公共Bean:

@Component
public class Users {
    
    
    @Bean
    public User user1() {
    
    
        User user = new User();
        user.setId(1);
        user.setName("Java"); // 【重点:名称是 Java】
        return user;
    }
}

A ⽤户使⽤时,进⾏了修改操作:

@Controller
public class BeanScopesController {
    
    
    @Autowired
    private User user1;
    public User getUser1() {
    
    
        User user = user1;
        System.out.println("Bean 原 Name:" + user.getName());
        user.setName("悟空"); // 【重点:进⾏了修改操作】
        return user;
    }
}

B ⽤户再去使⽤公共 Bean 的时候:

@Controller
public class BeanScopesController2 {
    
    
    @Autowired
    private User user1;
    public User getUser1() {
    
    
        User user = user1;
        return user;
    }
}

打印 A ⽤户和 B ⽤户公共 Bean 的值:

public class BeanScopesTest {
    
    
    public static void main(String[] args) {
    
    
        ApplicationContext context = new
                ClassPathXmlApplicationContext("spring-config.xml");
        BeanScopesController beanScopesController =
                context.getBean(BeanScopesController.class);
        System.out.println("A 对象修改之后 Name:" +
                beanScopesController.getUser1().toString());
        BeanScopesController2 beanScopesController2 =
                context.getBean(BeanScopesController2.class);
        System.out.println("B 对象读取到的 Name:" +
                beanScopesController2.getUser1().toString());
    }
}

执行结果如下:

在这里插入图片描述

原因分析:

操作以上问题的原因是因为 Bean 默认情况下是单例状态(singleton),也就是所有⼈的使⽤的都是同⼀个对象,之前我们学单例模式的时候都知道,使⽤单例可以很⼤程度上提⾼性能,所以在 Spring 中Bean 的作⽤域默认也是 singleton 单例模式

如何解决:

使用 @Scope 注释来设置作用域,如下

@Controller
public class Users {
    
    
    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)  //使用枚举 设置作用域
    public User user1(){
    
    //将这个 User 对象存储到了 spring中
        User user = new User();
        user.setId(209000804);
        user.setName("tanchen");
        return user;
    }

二、作⽤域定义

限定程序中变量的可⽤范围叫做作⽤域,或者说在源代码中定义变量的某个区域就叫做作⽤域

⽽ Bean 的作⽤域是指 Bean 在 Spring 整个框架中的某种⾏为模式,⽐如 singleton 单例作⽤域,就表示 Bean 在整个 Spring 中只有⼀份,它是全局共享的,那么当其他⼈修改了这个值之后,那么另⼀个⼈读取到的就是被修改的值

三、Bean 的 6 种作⽤域

Spring 容器在初始化⼀个 Bean 的实例时,同时会指定该实例的作⽤域。Spring有 6 种作⽤域,
最后四种是基于 Spring MVC ⽣效的:

  1. singleton:单例作⽤域
  2. prototype:原型作⽤域(多例作⽤域)
  3. request:请求作⽤域
  4. session:回话作⽤域
  5. application:全局作⽤域
  6. websocket:HTTP WebSocket 作⽤域

注意后 4 种状态是 Spring MVC 中的值,在普通的 Spring 项⽬中只有前两种

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默认选择该作⽤域

prototype

官⽅说明:Scopes a single bean definition to any number of object instances.
描述:每次对该作⽤域下的Bean的请求都会创建新的实例:获取Bean(即通过
applicationContext.getBean等⽅法获取)及装配Bean(即通过@Autowired注⼊)都是新的
对象实例。
场景:通常有状态的Bean使⽤该作⽤域

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
场景:⼀次http的请求和响应的共享Bean
备注:限定SpringMVC中使⽤

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实例
场景:⽤户回话的共享Bean, ⽐如:记录⼀个⽤户的登陆信息
备注:限定SpringMVC中使⽤

application(了解)

官⽅说明:Scopes a single bean definition to the lifecycle of a ServletContext. Only valid
in the context of a web-aware Spring ApplicationContext.
描述:在⼀个http servlet Context中,定义⼀个Bean实例
场景:Web应⽤的上下⽂信息,⽐如:记录⼀个应⽤的共享信息
备注:限定SpringMVC中使⽤

websocket(了解)

官⽅说明:Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in
the context of a web-aware Spring ApplicationContext.
描述:在⼀个HTTP WebSocket的⽣命周期中,定义⼀个Bean实例
场景:WebSocket的每次会话中,保存了⼀个Map结构的头信息,将⽤来包裹客户端消息
头。第⼀次初始化后,直到WebSocket结束都是同⼀个Bean。
备注:限定Spring WebSocket中使⽤

单例作⽤域(singleton)和全局作⽤域(application)区别

  1. singleton 是 Spring Core 的作⽤域;application 是 Spring Web 中的作⽤域;
  2. singleton 作⽤于 IoC 的容器,⽽ application 作⽤于 Servlet 容器

四、Bean 原理分析

4.1 Bean 执行流程

在这里插入图片描述

Bean 执⾏流程(Spring 执⾏流程):启动 Spring 容器 -> 实例化 Bean(分配内存空间,从⽆到有)-> Bean 注册到 Spring 中(存操作) -> 将 Bean 装配到需要的类中(取操作)

4.2 Bean ⽣命周期

所谓的⽣命周期指的是⼀个对象从诞⽣到销毁的整个⽣命过程,我们把这个过程就叫做⼀个对象的⽣命周期

Bean 的⽣命周期分为以下 5 ⼤部分:

  1. 实例化 Bean(为 Bean 分配内存空间)
  2. 设置属性(Bean 注⼊和装配)
  3. Bean 初始化
    a.实现了各种 Aware 通知的⽅法,如 BeanNameAware、BeanFactoryAware、
    b.ApplicationContextAware 的接⼝⽅法;
    c.执⾏ BeanPostProcessor 初始化前置⽅法;
    d.执⾏ @PostConstruct 初始化⽅法,依赖注⼊操作之后被执⾏;
    e.执⾏⾃⼰指定的 init-method ⽅法(如果有指定的话);
    f.执⾏ BeanPostProcessor 初始化后置⽅法。
  4. 使⽤ Bean
  5. 销毁 Bean
    销毁容器的各种⽅法,如 @PreDestroy、DisposableBean 接⼝⽅法、destroy-method

执⾏流程如下图所示:
在这里插入图片描述

实例化和初始化的区别:

实例化和属性设置是 Java 级别的系统“事件”,其操作过程不可⼈⼯⼲预和修改;⽽初始化是给
开发者提供的,可以在实例化之后,类加载完成之前进⾏⾃定义“事件”处理

上述流程比较抽象,我们举个例子:

  1. 先买房(实例化,从⽆到有)
  2. 装修(设置属性)
  3. 买家电,如洗⾐机、冰箱、电视、空调等([各种]初始化)
  4. ⼊住(使⽤ Bean)
  5. 卖出去(Bean 销毁)

⽣命周期演示

        import org.springframework.beans.factory.BeanNameAware;
        import org.springframework.stereotype.Component;
        import javax.annotation.PostConstruct;
        import javax.annotation.PreDestroy;
@Component
public class BeanLifeComponent implements BeanNameAware {
    
    
    @PostConstruct
    public void postConstruct() {
    
    
        System.out.println("执⾏ PostConstruct()");
    }
    public void init() {
    
    
        System.out.println("执⾏ BeanLifeComponent init-method");
    }
    @PreDestroy
    public void preDestroy() {
    
    
        System.out.println("执⾏:preDestroy()");
    }
    public void setBeanName(String s) {
    
    
        System.out.println("执⾏了 setBeanName ⽅法:" + s);
    }
}

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.bit.component">
</content:component-scan>
<beans>
<bean id="beanLifeComponent"
class="com.bit.component.BeanLifeComponent" init-method="init"></bean>
</beans>
</beans>

调⽤类:

import com.bit.controller.BeanLife;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanLifeTest {
    
    
    public static void main(String[] args) {
    
    
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        BeanLife life = context.getBean(BeanLife.class);
        System.out.println("执⾏ main ⽅法");
// 执⾏销毁⽅法
        context.destroy();
    }
}

思考:为什么要先设置属性在进⾏初始化呢?,不能颠倒顺序

@Service
public class UserService {
    
    
    public UserService() {
    
    
        System.out.println("调⽤ User Service 构造⽅法");
    }

    public void sayHi() {
    
    
        System.out.println("User Service SayHi.");
    }
}

@Controller
public class UserController {
    
    
    @Resource
    private UserService userService;

    @PostConstruct
    public void postConstruct() {
    
    
        userService.sayHi();
        System.out.println("执⾏ User Controller 构造⽅法");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_64317046/article/details/129936063