Spring 一文带你速懂Bean生命周期(singleton 和 prototype)

Spring 一文带你速懂Bean生命周期(singleton 和 prototype)

Bean生命周期(singleton 和 prototype)

关于Bean生命周期: Spring 根据 Bean 的作用域来选择管理方式。对于 singleton 作用域的 Bean,Spring 能够精确地知道该 Bean 何时被创建,何时初始化完成,以及何时被销毁;而对于 prototype 作用域的 Bean,Spring 只负责创建,当容器创建了 Bean 的实例后,Bean 的实例就交给客户端代码管理,Spring 容器将不再跟踪其生命周期。

那如何验证呢?

首先,你需要看一篇基础知识,大约需要5分钟,然后我们做个测试,答案大家自然就能明白Bean的生命周期。

链接: Spring Bean生命周期.

首先我们先测试单例模式singleton

代码如下

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-3.0.xsd">

init-method="init" destroy-method="destroy">

package net.biancheng;

public class HelloWorld {

private String message;

public void setMessage(String message) {

this.message = message;

}

public void getMessage() {

System.out.println("message : " + message);

}

private void init() {

System.out.println("测试xml配置的初始化方法");

}

private void destroy() {

System.out.println("测试xml配置的销毁方法");

}

}

package net.biancheng;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.AbstractApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {

public static void main(String[] args) {

//Spring实例

// ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

AbstractApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

HelloWorld obj = (HelloWorld) context.getBean("helloWorld");

obj.setMessage("对象A");//注意1-getBean两次对象

obj.getMessage();

context.registerShutdownHook();//注意2-只调用一次销毁

//测试单例模式和原型模式

HelloWorld obj2 = (HelloWorld) context.getBean("helloWorld");

obj2.getMessage();

}

}

测试xml配置的初始化方法

message : 对象A

message : 对象A

测试xml配置的销毁方法

所以,验证了:对于 singleton 作用域的 Bean,Spring 能够精确地知道该 Bean 何时被创建,何时初始化完成,以及何时被销毁;

Spring 知道Bean 所有生命周期,所以它调用了初始和销毁方法,又因为验证了单例是容器内只存在一个对象,所以只存在调用一次初始化方法,并且销毁方法最后才调用。

最后我们测试原型模式prototype

我们只改动xml配置

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-3.0.xsd">

init-method="init" destroy-method="destroy">

var foo = 'bar';

测试xml配置的初始化方法

message : 对象A

测试xml配置的初始化方法

message : Hello World!

所以,验证了:对于 prototype 作用域的 Bean,Spring 只负责创建,当容器创建了 Bean 的实例后,Bean 的实例就交给客户端代码管理,Spring 容器将不再跟踪其生命周期。

Spring 只负责创建,所以它调用了初始而不会调用销毁方法,又同时验证了原型模式每次通过 Spring 容器获取 Bean 时,容器都会创建一个 Bean 实例,所以会调用两次初始化方法。

🎯 相关推荐

新区怎么排队进去最快!对于不是通道玩家
best365官网下载

新区怎么排队进去最快!对于不是通道玩家

📅 07-08 👀 6455
cnckadv16安装教程(含详细安装方法)
365bet提款问题

cnckadv16安装教程(含详细安装方法)

📅 08-12 👀 2362
《舌尖上的中国2》美食英文说法大全
365bet提款问题

《舌尖上的中国2》美食英文说法大全

📅 06-28 👀 405