Spring中,对象的生命周期

为验证,我们写一个类,包括如下几个元素:

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

	public String getName() {
		System.out.println("get方法");
		return name;
	}

	public void setName(String name) {
		System.out.println("set方法");
		this.name = name;
	}
	
	public void init() {
		System.out.println("init");
	}
	public void destroy(){
		System.out.println("销毁");
	}
	
}

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= "userInfo" class="com.jd.vo.UserInfo" lazy-init="true" init-method="init" destroy-method="destroy"><!--scope可以是除"prototype"外其他任意值,因为scope为prototype时,destroy方法不执行-->
		<property name="name" value="Tom"></property>
	</bean>
</beans>

再创建一的测试类:

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("application.xml");//创建IOC容器并为xml中配置的类创建对象
		Object object = classPathXmlApplicationContext.getBean("userInfo");
		System.out.println(object);
	}
}

运行Test类:

观察结果,可知spring中,对象的生命周期为静态代码块->动态代码块->构造方法->set方法->init->方法->main方法->destroy方法 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值