文章目录
引言:
从前⾯的文章中
Spring的创建和使用
Spring更简单的读取和存储对象
我们可以看出 Spring 是⽤来读取和存储 Bean,因此在 Spring 中 Bean 是最核⼼的操作资源,所以接下来让我们再一起深⼊学习⼀下 Bean 对象吧😊😊😊
通过⼀个案例来看 Bean 作用域的问题
假设现在有⼀个公共的 Bean,提供给 A ⽤户和 B ⽤户使⽤,然⽽在使⽤的途中 A ⽤户却“悄悄”地修改了公共 Bean 的数据,导致 B ⽤户在使⽤时发⽣了预期之外的逻辑错误。(我们预期的结果是,公共 Bean 可以在各⾃的类中被修改,但不能影响到其他类。)
公共 Bean(UserBeans):
package bean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class UserBeans {
@Bean//【注意事项:只使用一个@Bean是无法将对象存储到容器中的】
public User user1(){
User user=new User();
user.setId(1);
user.setName("潘潘");// 【重点:名称是潘潘】
return user;
}
}
User:
package bean;
public class User {
private int id;
private String name;
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
A ⽤户使⽤时,进⾏了修改操作:
package bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@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 的时候:
package bean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class BeanScopesController2 {
@Autowired
private User user1;
public User getUser1() {
User user=user1;
return user;
}
}
打印 A ⽤户和 B ⽤户公共 Bean 的值:
import bean.BeanScopesController;
import bean.BeanScopesController2;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class BeanScopesTest {
public static void main(String[] args) {
//先得到上下文对象
ApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
//获取bean和使用bean
BeanScopesController scopesController=context.getBean(BeanScopesController.class);
System.out.println("A 对象修改之后 Name:" +scopesController.getUser1().toString());
BeanScopesController2 scopesController2=context.getBean(BeanScopesController2.class);
System.out.println("B 对象读取到的 Name:"+scopesController2.getUser1().toString());
}
}
执⾏结果如下:
操作以上问题的原因是因为 Bean默认情况下是单例状态(singleton),也就是所有⼈的使⽤的都是同⼀个对象,之前我们一起学习单例模式的时候知道,使⽤单例可以很⼤程度上提⾼性能,所以在 Spring 中Bean 的作⽤域默认也是 singleton 单例模式。
作用域定义
限定程序中变量的可⽤范围叫做作⽤域,或者说在源代码中定义变量的某个区域就叫做作⽤域。
而 Bean 的作⽤域是指 Bean 在 Spring 整个框架中的某种行为模式,⽐如 singleton 单例作⽤域,就表示 Bean 在整个 Spring 中只有⼀份,它是全局共享的,那么当其他⼈修改了这个值之后,那么另⼀个⼈读取到的就是被修改的值。
Bean 的 6 种作用域
Spring 容器在初始化⼀个 Bean 的实例时,同时会指定该实例的作⽤域。
- singleton: 单例作⽤域(默认)
- prototype: 原型作⽤域(多例模式)
- request: 请求作⽤域(Spring MVC)
- session: 回话作⽤域(Spring MVC)
- application: 全局作⽤域(Spring MVC)
- websocket: HTTP WebSocket 作⽤域(Spring WebSocket)
注意: 后 4 种状态是 Spring MVC 中的值,在普通的 Spring 项⽬中只有前两种。
singleton
描述: 该作⽤域下的Bean在IoC容器中只存在⼀个实例:获取Bean(即通过applicationContext.getBean等⽅法获取)及装配Bean(即通过@Autowired注⼊)都是同⼀
个对象。
场景: 通常⽆状态的Bean使⽤该作⽤域。⽆状态表示Bean对象的属性状态不需要更新
备注: Spring默认选择该作用域
prototype
描述: 每次对该作⽤域下的Bean的请求都会创建新的实例:获取Bean(即通过applicationContext.getBean等⽅法获取)及装配Bean(即通过@Autowired注⼊)都是新的对象实例。
场景: 通常有状态的Bean 使⽤该作⽤域
request
描述: 每次http请求会创建新的Bean实例,类似于prototype
场景: ⼀次http的请求和响应的共享Bean
备注: 限定SpringMVC中使用
session
描述: 在⼀个http session中,定义⼀个Bean实例
场景: ⽤户回话的共享Bean, ⽐如:记录⼀个⽤户的登陆信息
备注: 限定SpringMVC中使用
application
描述: 在⼀个http servlet Context中,定义⼀个Bean实例
场景: Web应⽤的上下⽂信息,⽐如:记录⼀个应⽤的共享信息
备注: 限定SpringMVC中使用
websocket
描述: 在⼀个HTTP WebSocket的⽣命周期中,定义⼀个Bea实例
场景: WebSocket的每次会话中,保存了⼀个Map结构的头信息,将⽤来包裹客户端消息头。第⼀次初始化后,直WebSocket结束都是同⼀个Bean。
备注: 限定Spring WebSocket中使用
单例作用域(singleton)和全局作用域(application)区别
- singleton 是 Spring Core 的作⽤域;application 是 Spring Web 中的作⽤域;
- singleton 作⽤于 IoC 的容器,而 application 作⽤于 Servlet 容器
设置 Bean 作用域
只需要在需要注入的对象上面去加相应的@Scope注解就可以了❗
@Scope标签既可以修饰方法也可以修饰类,@Scope有两种设置方式:
- 直接设置值:@Scope(“prototype”)
- 使用枚举设置(是类似于枚举的常量的方式):@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
我们从文章刚开始的那个例子可以看出,原来的值被A对象修改以后,B对象的值也跟着被更新了,那么我们就可以使用下面这两种方法来解决该问题⬇️⬇️⬇️
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Scope(“prototype”)
Bean 生命周期
所谓的⽣命周期指的是⼀个对象从诞生到销毁的整个生命过程,我们把这个过程就叫做⼀个对象的生命周期。
Bean 的⽣命周期分为以下 5 ⼤部分:
- 实例化 Bean(给Bean 分配内存空间)
- 设置属性(对象注⼊)
- Bean 初始化
a)执行各种通知(执行各种Aware)
b)执⾏ BeanPostProcessor 初始化前置⽅法
c)执行构造方法,两种执行方式,一种是执行 @PostConstruct ,另一种是执行 init-method
d)执⾏ BeanPostProcessor 初始化后置⽅法 - 使⽤ Bean
- 销毁 Bean
a)@PreDestroy
b) 重写 DisposableBean 接口方法
c) destroy-method
执行流程如下图所示:
实例化和初始化的区别
实例化和属性设置是 Java 级别的系统“事件”,其操作过程不可人工干预和修改;而初始化是给开发者提供的,可以在实例化之后,类加载完成之前进⾏⾃定义“事件”处理
具体示例代码
package bean;
import org.springframework.beans.factory.BeanNameAware;
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("执行 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="bean"> </content:component-scan>
<bean id="beanLifeComponent" class="bean.BeanLifeComponent" init-method="init">
</bean>
</beans>
调⽤类:
import bean.BeanLifeComponent;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App3 {
public static void main(String[] args) {
ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("spring-config.xml");
BeanLifeComponent beanLifeComponent=context.getBean("beanLifeComponent",BeanLifeComponent.class);
beanLifeComponent.use();
context.destroy();
}
}
最终结果如下: