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方法 

发布了91 篇原创文章 · 获赞 10 · 访问量 8013

猜你喜欢

转载自blog.csdn.net/Liuxiaoyang1999/article/details/104504594