Spring | Bean 作用域和生命周期

一、通过一个案例来看 Bean 作用域的问题

Spring 是用来读取和存储 Bean,因此在 Spring 中 Bean 是最核心的操作资源,所以接下来我们深入学习⼀下 Bean 对象

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

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

1、被修改的 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 原 Name: Java (原来的值)
A 对象修改之后 Name: 1:悟空 (被 A 对象修改)
B 对象读取到的 Name: 1:悟空 (B 对象中也跟着被更新了)


2、原因分析

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


二、作用域定义 Scope

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

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


1、Bean 的 6 种作用域

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

  1. singleton :单例作用域(默认)

  2. prototype :原型作用域(多例作用域)

  3. request :请求作用域(Spring MVC)

  4. session :回话作用域(Spring MVC)

  5. application :全局作用域(Spring MVC)

  6. websocket :HTTP WebSocket 作用域(Spring WebSocket)

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


2、设置 bean 作用域

@scope 标签既可以修饰方法,也可以修饰类,有两种设置方式:

  • 直接设置值:@Scope("prototype")
  • 类似枚举常量的设置:@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)

2.1、测试 Bean 默认是那种作用域

——UserBeans:

@Component
public class UserBeans {
    @Bean(name = "user1")
    public User getUser1() {
        User user = new User();
        user.setId(1);
        user.setName("zhangsan");
        return user;
    }

    @Bean(name = "user2")
    public User getUser2() {
        User user = new User();
        user.setId(2);
        user.setName("lisi");
        return user;
    }

    @Bean(name = "user3")
    public User getUser3() {
        User user = new User();
        user.setId(3);
        user.setName("Java");
        return user;
    }
}

——创建类 BeanScope1:

@Component
public class BeanScope1 {
    @Autowired // 注入 user3
    private User user3;

    public User getUser3() {
        User user = user3;
        user.setName("八戒");
        return user;
    }
}

——创建类 BeanScope2:

@Component
public class BeanScope2 {
    @Autowired
    private User user3;

    public User getUser3() {
        return user3;
    }
}

——测试:

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new
                ClassPathXmlApplicationContext("spring-config.xml");
        BeanScope1 beanScope1 = context.getBean(BeanScope1.class);
        User user1 = beanScope1.getUser3();
        System.out.println("BeanScope1" + user1);

        BeanScope2 beanScope2 = context.getBean(BeanScope2.class);
        User user2 = beanScope2.getUser3();
        System.out.println("BeanScope2" + user2);
    }
}

运行结果: 说明默认为单例

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘八戒’}


2.2、设置作用域

  • @Scope(“prototype”)
@Bean(name = "user3")
@Scope("prototype") // 原型模式,每次请求生成一个对象
public User getUser3() {
    User user = new User();
    user.setId(3);
    user.setName("Java");
    return user;
}

运行结果:

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘Java’}

  • @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    @Bean(name = "user3")
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    public User getUser3() {
        User user = new User();
        user.setId(3);
        user.setName("Java");
        return user;
    }

在这里插入图片描述

运行结果:

BeanScope1User{id=3, name=‘八戒’}
BeanScope2User{id=3, name=‘Java’}


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


2.4、prototype

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


2.5、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中使⽤


2.6、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中使⽤


2.7、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中使⽤


2.8、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中使⽤


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

项目类型不同: singleton 是 Spring Core 的作⽤域;application 是 Spring Web 中的作⽤域;
作用容器不同: singleton 作⽤于 IoC 的容器,而 application 作⽤于 Servlet 容器


3、Bean 原理分析

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

在这里插入图片描述


三、Bean 生命周期

1、5 个流程

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

Bean 的生命周期分为以下 5 大部分:

  1. 实例化 Bean(为 Bean 分配内存空间)

  2. 设置属性(Bean 注⼊和装配)

  3. Bean 初始化

    • 实现了各种 Aware 通知的方法,如 BeanNameAware、BeanFactoryAware、ApplicationContextAware 的接口方法;

    • 执行 BeanPostProcessor 初始化前置方法;

    • 执行构造方法,有两种执行方式:

    • 注解: @PostConstruct 初始化方法,依赖注⼊操作之后被执行;

    • xml:执行自己指定的 init-method 方法(如果有指定的话);<bean init-method=""></bean>

    • 如果两个都设置了,先执行注解,

    • 执行 BeanPostProcessor 初始化后置方法

  4. 使⽤ Bean

  5. 销毁 Bean

    • 销毁容器的各种方法,如 @PreDestroy (注解)、DisposableBean 接口方法、destroy-method (xml)

2、实例化和初始化的区别

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


3、生命流程的“故事”

Bean 的生命流程看似繁琐,但咱们可以以生活中的场景来理解它,比如我们现在需要买一栋房子,那么我们的流程是这样的:

  1. 先买房(实例化,从无到有);

  2. 装修(设置属性);

  3. 买家电,如洗衣机、冰箱、电视、空调等([各种]初始化);

  4. 入住(使用 Bean);

  5. 卖出去(Bean 销毁)


4、生命周期演示

——创建类 BeanLifeComponent:

// @Component // 在 xml 中 使用 bean 标签注入了,不需要类注解
public class BeanLifeComponent implements BeanNameAware {
    @PostConstruct
    public void postConstruct() {
        System.out.println("执⾏ @PostConstruct()");
    }

    public void init() {
        System.out.println("执⾏ init-method");
    }
    
    public void use() {
        System.out.println("使用 bean");
    }
    
    @PreDestroy
    public void preDestroy() {
        System.out.println("执⾏ @PreDestroy");
    }

    public void setBeanName(String s) {
        System.out.println("执⾏了 Aware 通知");
    }
}

——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.beans"></content:component-scan>

    <bean id="beanLifeComponent" class="com.beans.BeanLifeComponent" init-method="init"></bean>

</beans>

——调⽤类:

public class App {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
        BeanLifeComponent beanLifeComponent = 
            context.getBean("beanLifeComponent", BeanLifeComponent.class);
        beanLifeComponent.use();
        context.destroy(); // 注销上下文对象
    }
}

运行结果:

执行了 Aware 通知
执行 @PostConstruct()
执行 init-method
使用 bean
执行 @PreDestroy


2、为什么先设置属性再初始化

也就是 步骤 2 和 步骤 3 的顺序,能不能打个颠倒?

@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 构造⽅法");
    }
}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三春去后诸芳尽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值