Spring之bean单例与多例

Bean的生命周期

在 Spring 中 Bean 的生命周期可以分为以下阶段:

1. 实例化:当容器收到 Bean 的定义后,会通过反射机制实例化一个 Bean 对象。

2. 属性赋值:在实例化后,容器会将 Bean 的属性注入到对象中,包括依赖的其他 Bean。

3. 初始化:在 Bean 属性注入完成后,会调用 Bean 的初始化方法(如果有的话)。

4. 使用:当 Bean 初始化完成后,就可以被容器使用了,比如调用 Bean 的方法。

5. 销毁:当容器关闭或者销毁 Bean 的时候,会调用 Bean 的销毁方法(如果有的话)。

这就是 Spring 中 Bean 的基本生命周期。在每个阶段,Spring 提供了一些扩展点,可以在这些扩展点上做一些自定义的处理,比如 BeanPostProcessor 接口提供了 beforeInitialization 和 afterInitialization 两个扩展点,可以在 Bean 初始化的前后做一些自定义的处理。

bean的初始化

Bean的初始化主要分为两个阶段:
  1. 实例化阶段:在容器启动后,根据配置文件中的Bean定义,通过反射或工厂方法等方式实例化Bean对象。

  2. 初始化阶段:在Bean实例化后,容器会调用Bean的初始化方法进行初始化。在Spring中,有多种方式可以定义Bean的初始化方法,包括:

  • 实现InitializingBean接口,并实现afterPropertiesSet()方法;
  • 使用@Bean注解中的initMethod属性指定初始化方法;
  • 在XML配置文件中使用init-method属性指定初始化方法。
  • 在初始化方法执行完成后,Bean就可以被容器使用了。

单例与多例的认识

沉默的单例:

单例模式是指一个类只允许创建一个实例,这个实例在整个应用程序中都是唯一的。通过使用单例模式,可以确保一个类只有一个实例,并提供全局访问点

import java.util.List;

public class ParamAction {
	private int age;
	private String name;
	private List<String> hobby;
	private int num = 1;
	// private UserBiz userBiz = new UserBizImpl1();

	public ParamAction() {
		super();
	}

	public ParamAction(int age, String name, List<String> hobby) {
		super();
		this.age = age;
		this.name = name;
		this.hobby = hobby;
	}

	public void execute() {
		// userBiz.upload();
		// userBiz = new UserBizImpl2();
		System.out.println("this.num=" + this.num++);
		System.out.println(this.name);
		System.out.println(this.age);
		System.out.println(this.hobby);
	}
}

spring的配置文件:

<?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的生命周期-->
    <bean id="paramAction" class="com.xissl.beanLife.ParamAction">
        <constructor-arg name="name" value="三丰"></constructor-arg>
        <constructor-arg name="age" value="21"></constructor-arg>
        <constructor-arg name="hobby">
            <list>
                <value>抽烟</value>
                <value>烫头</value>
                <value>大保健</value>
            </list>
        </constructor-arg>
    </bean>

</beans>
 初始化:
package com.xissl.beanLife;

public class InstanceFactory {
	public void init() {
		System.out.println("初始化方法");
	}

	public void destroy() {
		System.out.println("销毁方法");
	}

	public void service() {
		System.out.println("业务方法");
	}
}

spring的单例测试:
package com.xissl.beanLife;

import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/*
 * spring	bean的生命週期
 * spring	bean的单例多例
 */
public class Demo2 {
	// 体现单例与多例的初始化的时间点 instanceFactory
	@Test
	public void test2() {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-context.xml");
	}

}

spring配置上下文 :

<bean id="instanceFactory" class="com.xissl.beanLife.InstanceFactory"
          scope="singleton" init-method="init" destroy-method="destroy"></bean>

多例:

多例模式是指一个类可以生成多个实例,但是这些实例都属于同一个类。每个实例都有一个唯一的标识符,可以通过该标识符来区分不同实例之间的差异。

<bean id="paramAction" class="com.xissl.beanLife.ParamAction" scope="prototype">
        <constructor-arg name="name" value="三丰"></constructor-arg>
        <constructor-arg name="age" value="21"></constructor-arg>
        <constructor-arg name="hobby">
            <list>
                <value>抽烟</value>
                <value>烫头</value>
                <value>大保健</value>
            </list>
        </constructor-arg>
    </bean>

    <bean id="instanceFactory" class="com.xissl.beanLife.InstanceFactory"
          scope="prototype" init-method="init" destroy-method="destroy"></bean>

bean的单例多例总结:

bean是单例还是多例的,bean沉默是单例,但是他可以配置多例

在Spring中,有两个类型,一个是单例一个和多例,一个Bean同学,要么是单例要么是多例。

prototype(多例)和singleton(单例)

在Spring中,bean的Scope常被定义的两种模式:prototype(多例)和singleton(单例)。

singleton(单例):只有一个共享的实例存在,所有对这个bean的请求都会返回这个唯一的实例。

此取值时表明容器中创建时只存在一个实例,所有引用此bean都是单一实例。如同每个国家都有一个总统,国家的所有人共用此总统,而这个国家就是一个spring容器,总统就是spring创建的类的bean,国家中的人就是其它调用者,总统是一个表明其在spring中的scope为singleton,也就是单例模型。

此外,singleton类型的bean定义从容器启动到第一次被请求而实例化开始,只要容器不销毁或退出,该类型的bean的单一实例就会一直存活,典型单例模式,如同servlet在web容器中的生命周期。

prototype(多例):对这个bean的每次请求都会创建一个新的bean实例,类似于new。

spring容器在进行输出prototype的bean对象时,会每次都重新生成一个新的对象给请求方,虽然这种类型的对象的实例化以及属性设置等工作都是由容器负责的,但是只要准备完毕,并且对象实例返回给请求方之后,容器就不在拥有当前对象的引用,请求方需要自己负责当前对象后继生命周期的管理工作,包括该对象的销毁。也就是说,容器每次返回请求方该对象的一个新的实例之后,就由这个对象“自生自灭”。

 比如:

如同分苹果,将苹果的bean的scope属性声明为prototype,在每个人领取苹果的时候,我们都是发一个新的苹果给他,发完之后,别人爱怎么吃就怎么吃,爱什么时候吃什么时候吃,但是注意吃完要把苹果核扔到垃圾箱!对于那些不能共享使用的对象类型,应该将其定义的scope设为prototype。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Alone秋

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

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

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

打赏作者

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

抵扣说明:

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

余额充值