sping对象的生命周期

本文探讨了Spring对象的生命周期,从静态代码块到动态代码块,再到构造方法、setter方法、getter方法,以及init和destroy方法的调用顺序。通过XML配置文件的调整,展示了singleton和prototype作用域对destroy方法的影响,强调了IoC容器关闭对于触发destroy方法的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,我们在一个类中写下与生命周期相关的多种元素

package com.jd.vo;

public class UserInfo {
	
	static {
		System.out.println("静态代码块");
	}
	
	{
		System.out.println("非静态代码块");
	}
	
	private String name;
	
	public String getName() {
		System.out.println("getter方法");
		return name;
	}

	public void setName(String name) {
		System.out.println("setter方法");
		this.name = name;
	}

	public UserInfo() {
		System.out.println("构造方法");
	}
	
	public void init() {
		System.out.println("init");
	}
	
	public void destroy() {
		System.out.println("destroy");
	}
}

并创建test类来测试其输出

package com.jd.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("application.xml");
		Object object = applicationContext.getBean("d");
		applicationContext.close();
	}
}

配置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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="d" class="com.jd.vo.UserInfo" lazy-init="true" scope="prototype">
		<property name="name" value="Tom"></property>
	</bean>
</beans>

执行main方法,输出为

可以看到spring对象的生命周期为静态代码块->动态代码块->构造方法->set方法,我们注意到,由于init和destroy的值均为默认,导致init方法和destroy方法未能输出。

修改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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="d" class="com.jd.vo.UserInfo" lazy-init="true" scope="prototype" init-method="init" destroy-method="destroy">
		<property name="name" value="Tom"></property>
	</bean>
</beans>

输出为

 我们发现,init方法在setter之后输出了,但destroy方法仍未输出,这是由于scope的值设定为了prototype,如果我们改为singlton,输出则变为

并且如果我们在main方法中没有调用close方法销毁IoC容器,那么destroy方法也不会输出。 

综上,spring对象的生命周期为静态代码块->动态代码块->构造方法->setter方法->getter方法->init->destroy

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值