Bean 的作用域和生命周期

目录

1.案例展示 Bean 作用域的问题

1.1  singletion: 单例作用域

1.2 prototype: 原型作用域(多例作用域)

2. Bean 的 6 种作用域

2.1 singletion: 单利作用域

2.2 prototype: 原型作用域(多例作用域)

2.3 request: 请求作用域

2.4 session: 回话作用域

2.5 application: 全局作用域

2.6 websocket:HTTP WebSocket 作⽤域

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

3.Bean 原理分析

4. Bean 生命周期


1.案例展示 Bean 作用域的问题

1.1  singletion: 单例作用域

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

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

被修改的 Bean 案例

公共 Bean 

@Component
public class UserBeans {
    @Bean
    public User user1() {
        User user1 = new User();
        user1.setId(1);
        user1.setName("黄小小");
        return user1;
    }

}

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 中 Name 的值:

public class App2 {
    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().getName());

        BeanScopesController2 beanScopesController2 = context.getBean(BeanScopesController2.class);
        System.out.println("B 对象获取 Name: " + beanScopesController2.getUser1().getName());
      
    }
}

 原因分析

操作以上问题的原因是因为 Bean 默认情况下是单例状态(singleton),也就是所有⼈的使⽤的都是同⼀个对象。

使⽤单例可以很⼤程度上提⾼性能,所以在 Spring 中 Bean 的作⽤域默认也是 singleton 单例模式。

1.2 prototype: 原型作用域(多例作用域)

直接在公共Bean 中加入注解 @Scope("prototype") ,其他的不改变即可

@Component
public class UserBeans {
    @Bean
    @Scope("prototype") //多例作用域
    public User user1() {
        User user1 = new User();
        user1.setId(1);
        user1.setName("黄小小");
        return user1;
    }

}

看 A 和 B 获取对象结果

 

作⽤域定义 

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

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

2. Bean 的 6 种作用域

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

1. singletion: 单利作用域

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

3.request: 请求作用域

4.session: 回话作用域

5.application: 全局作用域

6. websocket:HTTP WebSocket 作⽤域

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

2.1 singletion: 单利作用域

官⽅说明:(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.2 prototype: 原型作用域(多例作用域)

官⽅说明:(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.3 request: 请求作用域

描述:每次http请求会创建新的Bean实例,类似于prototype

场景:⼀次http的请求和响应的共享Bean

备注:限定SpringMVC中使⽤

2.4 session: 回话作用域

描述:在⼀个http session中,定义⼀个Bean实例

场景:⽤户回话的共享Bean, ⽐如:记录⼀个⽤户的登陆信息

备注:限定SpringMVC中使⽤

2.5 application: 全局作用域

描述:在⼀个http servlet Context中,定义⼀个Bean实例

场景:Web应⽤的上下⽂信息,⽐如:记录⼀个应⽤的共享信息

备注:限定SpringMVC中使⽤

2.6 websocket:HTTP WebSocket 作⽤域

描述:在⼀个HTTP WebSocket的⽣命周期中,定义⼀个Bean实例

场景:WebSocket的每次会话中,保存了⼀个Map结构的头信息,将⽤来包裹客户端消息

头。第⼀次初始化后,直到WebSocket结束都是同⼀个Bean。

备注:限定Spring WebSocket中使⽤

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

singleton 是 Spring Core 的作⽤域;application 是 Spring Web 中的作⽤域;

singleton 作⽤于 IoC 的容器,⽽ application 作⽤于 Servlet 容器

3.Bean 原理分析

Bean 执⾏流程(Spring 执⾏流程):

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

4. Bean 生命周期

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

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

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

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

3.Bean 初始化

实现了各种 Aware 通知的⽅法,如 BeanNameAware、BeanFactoryAware、

ApplicationContextAware 的接⼝⽅法;

执⾏ BeanPostProcessor 初始化前置⽅法;

执⾏ @PostConstruct 初始化⽅法,依赖注⼊操作之后被执⾏;

执⾏⾃⼰指定的 init-method ⽅法(如果有指定的话);

执⾏ BeanPostProcessor 初始化后置⽅法。

4.使⽤ Bean

5.销毁 Bean

销毁容器的各种⽅法,如 @PreDestroy、DisposableBean 接口方法、destroy-method

 实例化和初始化的区别

实例化和属性设置是 Java 级别的系统“事件”,其操作过程不可⼈⼯⼲预和修改;

⽽初始化是给开发者提供的,可以在实例化之后,类加载完成之前进⾏⾃定义“事件”处理。

生命周期的代码演示  

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

调⽤类:


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();
    }
}

猜你喜欢

转载自blog.csdn.net/m0_60494863/article/details/125854659