Bean 作用域和生命周期

        Bean 作为 Spring 容器中最主要的对象,其作用域和生命周期非常重要;

1. 案例演示 Bean 作用域:

        首先有一个公共的 Bean:AnimalsBeans

@Component
public class AnimalsBeans {
    @Bean
    public Animal myAnimal() {
        Animal animal = new Animal();
        animal.setType("小狗");
        return animal;
    }
}

        此时来了两个用户,用户1想拿到这个 Bean,再把 Bean 修改:

@Controller
public class AnimalController {
    @Autowired
    private Animal animal;

    public void animal() {
        System.out.println("原来的:" + animal);
        // 修改 Bean
        animal.setType("小猫");
        System.out.println("修改后:" + animal);
    }
}

        用户1拿到后,调用启动类,查看结果:

public class App {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        AnimalController animalController = context.getBean("animalController",AnimalController.class);
        animalController.animal();
    }
}

        可以看到,成功拿到初始的animal,还成功将修改了;

        但是问题来了,现在又有一个用户2,在用户1的基础上,他也想拿到这个公共的 Bean,那请问他拿到的会是修改前的还是修改后的值呢?

@Controller
public class AnimalController2 {
    @Autowired
    private Animal animal;

    public void animal() {
        System.out.println("拿到的:" + animal);
    }
}
public class App {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        AnimalController animalController = context.getBean("animalController",AnimalController.class);
        animalController.animal();
        AnimalController2 animalController2 = context.getBean("animalController2", AnimalController2.class);
        animalController2.animal();
    }
}

         可见用户2拿到的是用户1修改过的 Bean;但是如果没有用户1,用户2直接拿到的确实是在最初的 Bean;

public class App {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        AnimalController2 animalController2 = context.getBean("animalController2", AnimalController2.class);
        animalController2.animal();
    }
}

         造成这种修改一次全被修改的问题,就是因为 Spring 框架默认使用单例模式存储 Bean,要想实现各自拿到的 Bean 不受其他用户影响,可以借助注解设置 Bean 的作用域;


2.Bean 的作用域:

2.1 Bean 的 6 种作用域:

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

注意:只有前两种适用于普通 Spring 项目中,后四种是 Spring MVC 才使用的;

① singleton:

  • 单例作用域,Spring 默认使用该作用域;
  • 描述:在该作用域下,Bean 在 IoC 容器中只存在一个实例(无论何时取到的都是同一个 Bean 对象);
  • 场景:通常是无状态的 Bean 使用;(无状态:Bean 对象的属性状态不用更新);

② prototype:

  • 原型作用域(多例作用域);
  • 描述:每次请求该作用域下的 Bean 时都会创建新的实例;
  • 场景:通常有状态的 Bean 使用该作用域;

③ request:

  • 请求作用域;
  • 描述:每次发起 HTTP 请求都会创建一个 Bean 对象;
  • 场景:一次 HTTP 请求和响应的共享 Bean;用于SpringMVC中;

④ session:

  • 会话作用域;
  • 描述:每次 http session 会话共享的一个 Bean 对象;

⑤ websocket:

  • 描述:在⼀个HTTP WebSocket的⽣命周期中,定义⼀个Bean实例;
  • 场景:WebSocket的每次会话中,保存了⼀个Map结构的头信息,将用来包裹客户端消息头。第⼀ 次初始化后,直到WebSocket结束都是同⼀个Bean。

⑥ application:

  • 全局作用域;
  • 适用于 Spring Web 作用域和 Servlet 容器;

2.2 设置 Bean 作用域:

        了解了这么多作用域,其实这里真正能使用的只有 Singleton 和 prototype;对上述代码中的 Bean 设置成多例作用域;

        Bean 的作用域需要使用 @Scope 标签来声明:

        两种写法:

       Scope("prototype") 或 Scope("ConfigurableBeanFactory.SCOPE_PROTOTYPE"):

@Component
public class AnimalsBeans {
    @Scope("prototype")
    @Bean
    public Animal myAnimal() {
        Animal animal = new Animal();
        animal.setType("小狗");
        return animal;
    }
}

        Scope("ConfigurableBeanFactory.SCOPE_PROTOTYPE") 这种写法是把标签中的字符串用自带的接口代替,作用是一样的

此时执行代码,用户2拿到的就是属于自己的那份,没有被修改过的,新的 Bean 对象;

 


3. Bean 的生命周期:

        了解 Bean 的生命周期之前先要了解 Spring 的执行流程:

3.1 Spring 执行流程:

        这只是一个简单的流程:

        

3.2 Bean 生命周期:

Bean 的生命周期分为 5 部分:

  1. 实例化 Bean(为 Bean 分配内存空间);
  2. 设置属性(Bean 的属性注入和装配);
    1. 执行所需通知(实现很多Aware通知方法);
    2. 初始化前置方法(BeanPostProcessor方法);
    3. 初始化方法(两种实现方式:xml方式和注解方式);
    4. 初始化后置方法(BeanPostProcessor方法);
  3. 使用 Bean;
  4. 销毁 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"
       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.java.demo"></content:component-scan>

    <beans>
        <bean id="beanLife" class="com.java.demo.life.BeanLife" init-method="myInit"></bean>
    </beans>
</beans>
public class BeanLife implements BeanNameAware, BeanPostProcessor {
    @Override
    public void setBeanName(String s) {
        System.out.println("执行了通知 BeanName:" + s);
    }

    // xml方式初始化
    public void myInit() {
        System.out.println("XML 方式初始化");
    }
    // 注解方式初始化
    @PostConstruct
    public void doPostConstruct() {
        System.out.println("注解的 初始化操作");
    }

    public void sayHi() {
        System.out.println("sayHi~");
    }

    @PreDestroy
    public void doPreDestroy() {
        System.out.println("do PreDestroy");
    }
}
public class App {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("spring-config.xml");
        BeanLife beanLife = context.getBean("beanLife", BeanLife.class);
        beanLife.sayHi();
        context.destroy();
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

@糊糊涂涂

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

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

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

打赏作者

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

抵扣说明:

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

余额充值