5、Spring之bean的作用域和生命周期

这篇具有很好参考价值的文章主要介绍了5、Spring之bean的作用域和生命周期。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

5.1、bean的作用域

5.1.1、单例(默认且常用)

5.1.1.1、配置bean

5、Spring之bean的作用域和生命周期

注意:当bean不配置scope属性时,默认是singleton(单例)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="org.rain.spring.pojo.Student"></bean>

</beans>

5.1.1.2、测试

5、Spring之bean的作用域和生命周期

由控制台日志可知,此时ioc获取到的两个bean本质上是同一个对象

    @Test
    public void testScope() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-scope.xml");
        Student student1 = applicationContext.getBean(Student.class);
        Student student2 = applicationContext.getBean(Student.class);
        System.out.println(student1 == student2);
    }

5.1.2、多例

5.1.2.1、配置bean

5、Spring之bean的作用域和生命周期

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
    scope属性:设置bean的作用域
        当属性值为singleton时,在IOC容器中这个bean的对象始终为单实例;且创建对象的时机是IOC容器初始化时
        当属性值为prototype时,在IOC容器中这个bean的对象有多个实例;且创建对象的时机是获取bean时
    -->
    <bean id="student" class="org.rain.spring.pojo.Student" scope="prototype"></bean>

</beans>

5.1.2.2、测试

5、Spring之bean的作用域和生命周期

由控制台日志可知,此时ioc获取到的两个bean本质上是不同的对象

5.1.3、其他作用域

如果是在WebApplicationContext环境下还会有另外两个作用域(但不常用):

  • request:在一个请求范围内有效

  • session:在一个会话范围内有效

5.2、bean的生命周期

5.2.1、创建User类

5、Spring之bean的作用域和生命周期

package org.rain.spring.pojo;

/**
 * @author liaojy
 * @date 2023/8/3 - 23:59
 */
public class User {

    private Integer id;
    private String username;
    private String password;
    private Integer age;

    public User() {
        System.out.println("生命周期1:创建对象");
    }

    public User(Integer id, String username, String password, Integer age) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        System.out.println("生命周期2:依赖注入");
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public void initMethod(){
        System.out.println("生命周期3:初始化");
    }

    public void destroyMethod(){
        System.out.println("生命周期4:销毁");
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

5.2.2、配置bean

5、Spring之bean的作用域和生命周期

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
        init-method属性:指定初始化方法
        destroy-method属性:指定销毁方法
    -->
    <bean id="user" class="org.rain.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod">
        <property name="id" value="1"></property>
        <property name="username" value="张三"></property>
        <property name="password" value="123"></property>
        <property name="age" value="11"></property>
    </bean>

</beans>

5.2.3、测试

5、Spring之bean的作用域和生命周期

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子接口,扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
        ioc.close();
    }

5.3、作用域对生命周期的影响

5.3.1、作用域为单例时

5.3.1.1、配置bean

5、Spring之bean的作用域和生命周期

    <bean id="user" class="org.rain.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod">
        <property name="id" value="1"></property>
        <property name="username" value="张三"></property>
        <property name="password" value="123"></property>
        <property name="age" value="11"></property>
    </bean>

5.3.1.2、测试

5、Spring之bean的作用域和生命周期

由控制台日志可知,当bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时执行

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子接口,扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
    }

5.3.2、作用域为多例时

5.3.2.1、配置bean

5、Spring之bean的作用域和生命周期

    <bean id="user" class="org.rain.spring.pojo.User" init-method="initMethod" destroy-method="destroyMethod" scope="prototype">
        <property name="id" value="1"></property>
        <property name="username" value="张三"></property>
        <property name="password" value="123"></property>
        <property name="age" value="11"></property>
    </bean>

5.3.2.2、测试

5、Spring之bean的作用域和生命周期

由控制台日志可知,当bean的作用域为多例时,生命周期的前三个步骤会在获取bean时执行

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子接口,扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
    }

5.4、bean的后置处理器

5.4.1、创建bean的后置处理器

5、Spring之bean的作用域和生命周期

注意:自定义的bean后置处理器,需要实现BeanPostProcessor接口

package org.rain.spring.process;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * @author liaojy
 * @date 2023/8/4 - 23:52
 */
public class MyBeanProcessor implements BeanPostProcessor {
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanProcessor-->后置处理器postProcessBeforeInitialization");
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("MyBeanProcessor-->后置处理器postProcessAfterInitialization");
        return bean;
    }
}

5.4.2、配置bean的后置处理器

5、Spring之bean的作用域和生命周期

注意:bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行

    <!-- bean的后置处理器要放入IOC容器才能生效 -->
    <bean id="myBeanPostProcessor" class="org.rain.spring.process.MyBeanProcessor"></bean>

5.4.3、测试

5、Spring之bean的作用域和生命周期

由控制台日志可知,bean的后置处理器会在生命周期的初始化前后添加额外的操作

    @Test
    public void testLifecycle(){
        //ConfigurableApplicationContext是ApplicationContext子接口,扩展了刷新和关闭容器的方法
        ConfigurableApplicationContext ioc = new ClassPathXmlApplicationContext("spring-lifecycle.xml");
        User user = ioc.getBean(User.class);
        System.out.println(user);
        ioc.close();
    }

5.5、具体的生命周期过程

  • bean对象创建(调用无参构造器)

  • 给bean对象设置属性

  • bean对象初始化之前操作(由bean的后置处理器负责)

  • bean对象初始化(需在配置bean时指定初始化方法)

  • bean对象初始化之后操作(由bean的后置处理器负责)

  • bean对象就绪可以使用

  • bean对象销毁(需在配置bean时指定销毁方法)

  • IOC容器关闭文章来源地址https://www.toymoban.com/news/detail-624592.html

到了这里,关于5、Spring之bean的作用域和生命周期的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 5、Spring之bean的作用域和生命周期

    5.1.1.1、配置bean 注意:当bean不配置scope属性时,默认是singleton(单例) 5.1.1.2、测试 由控制台日志可知,此时ioc获取到的两个bean本质上是同一个对象 5.1.2.1、配置bean 5.1.2.2、测试 由控制台日志可知,此时ioc获取到的两个bean本质上是不同的对象 如果是在WebApplicationContext环境下

    2024年02月14日
    浏览(30)
  • Spring系列4 -- Bean的作用域和生命周期

    目录 1. 案例 2. 作用域定义 2.1 Bean的6种作用域 2.2 设置作用域 3. Sring的执行流程 4. Bean的生命周期 思考: 为什么不是先进行初始化然后再进行设置属性呢?         假设现在有⼀个公共的 Bean,提供给 A ⽤户和 B ⽤户使⽤,然⽽在使⽤的途中 A ⽤户却“悄悄”地修改了公共

    2024年02月15日
    浏览(27)
  • 【Spring学习】Bean对象的作用域和生命周期,了解了这些你就真正熟悉spring框架了.

    前言: 大家好,我是 良辰丫 ,我们已经学会了Spring的存取,今天我们将一起来学习Bean对象的作用域和生命周期.💌💌💌 🧑个人主页:良辰针不戳 📖所属专栏:javaEE进阶篇之框架学习 🍎励志语句:生活也许会让我们遍体鳞伤,但最终这些伤口会成为我们一辈子的财富。 💦期

    2024年02月07日
    浏览(52)
  • @Autowired和@Resource注解之间的关系区别,Bean的作用域和生命周期,Spring的执行流程

    目录 一. @Autowired 和 @Resource 注解 二. Bean的作用域  1. singleton(单例模式) 2. prototype(原型模式)(多例模式) 3. 请求作用域:request 4. 会话作用域:session 三. Spring 的执行流程 四. Bean 的生命周期   1. 实例化  2. 设置属性  3. Bean 初始化      3.1 执行各种各种 Aware 通知;     

    2024年02月04日
    浏览(48)
  • Bean作用域和生命周期

    hi,今天为大家带啦Bean的作用域和生命周期的相关知识 Bean的作用域和我们之前学过的不一样,我们之前学的作用域是一个范围,而现在指的是 Bean在Spring框架中的某种行为模式,也就是一个动作. 这样干巴巴的说看我可能无法理解,我们来举个例子 创建一个公共类的一个公共对象

    2024年02月15日
    浏览(42)
  • Bean 作用域和生命周期

    Spring 容器是用来存储和读取 Bean 的 , 因此 Bean 是 Spring 中最核心的操作资源. 编写代码过程中 , bean 对象如果有多个属性 , 创建 Getter , Setter, 构造方法 等方法 , 会产生大量冗长的代码. 那么为了使代码更加简洁 , 我们可以使用 Lombok 框架 , 只需要一行注释 , 就可以避免大量冗长

    2024年02月05日
    浏览(69)
  • Bean的作用域和生命周期

    目录 1.作⽤域定义 1.1Bean的6个作用域 1.singleton:单例作用域 2.prototype:多例作用域 3.request:请求作用域 4.session:会话作用域 5.application:全局作用域 6.websocket:HTTP WebSocket作用域 单例作⽤域(singleton) VS 全局作⽤域(application) 1.2设置作用域 1.直接设置值@Scope(\\\"potptype\\\") 2.用枚举设置:@Scop

    2024年02月02日
    浏览(77)
  • 【JavaEE进阶】Bean 作用域和生命周期

    注意在此例子中需要用到lombok lombok是什么? Lombok 是一个 Java 库,它通过注解的方式来简化 Java 代码的编写。它提供了一组注解,让我们可以通过在代码中添加这些注解来自动生成样板式的代码,如 getter、setter、构造函数、toString 等。 使用 Lombok 可以有效地减少冗余的样板代

    2024年02月12日
    浏览(38)
  • Spring Bean作用域与生命周期

    目录 Bean的作用域: Bean有六大行为模式 1、singleton:单例模式(默认) 2、prototype: 原型模式(多例模式) 3、request: 请求作用域(Spring MVC) 4、session: 会话作用域(Spring MVC) 5、application: 全局作用域(Spring MVC) 6、websocket: HTTP WebSocket 作用域(Spring WebSocket) applicationContext和singleton的区别  Bea

    2024年02月02日
    浏览(31)
  • 【Spring】Bean的作用域与生命周期详情:请简述Spring的执行流程并分析Bean的生命周期?

     我们都知道,Spring框架为开发人员提供了很多便捷,这使得开发人员能够更加专注于应用程序的核心业务逻辑,而不需要花费大量时间和精力在技术细节上。作为一个包含众多工具方法的IoC容器,存取JavaBean是其极为重要的一个环节。本文就对Spring中的Bean的作用域和生命周

    2024年02月12日
    浏览(38)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包