初识Spring(五)————Spring Bean生命周期

Bean对象生命周期流程

①通过构造方法或工厂方法创建bean对象,
②为bean属性赋值,
③调用 bean 的初始化方法,即init-method指定方法,
④bean实例化完毕,可以使用,
⑤容器关闭, 调用 bean 的销毁方法,即destroy-method指定方法。
init-method:在设置bean的属性后执行的自定义初始化方法,注意:①、该方法不能有参数;②、对象每创建一次就会执行一次该方法
destroy-method:该参数中的方法只有bean标签属性scope为singleton且关闭Spring IOC容器时才会被调用,注意:该方法不能有参数

下面来验证流程

package com.spring.minor;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StuTest {

	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("bean.xml");
		applicationContext.getBean("student");
		applicationContext.close();
	}
}


class Student {

	public Student() {
		System.out.println("student构造方法");
	}
	
	public void a() {
		System.out.println("init方法");
	}
	public void b() {
		System.out.println("destory方法");
	}
	
}

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="student" class="com.spring.minor.Student" init-method="a" destroy-method="b"></bean>
</beans>

输出如下

七月 10, 2019 12:43:54 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@817b38: startup date [Wed Jul 10 12:43:54 CST 2019]; root of context hierarchy
七月 10, 2019 12:43:54 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [bean.xml]
student构造方法
init方法
七月 10, 2019 12:43:55 下午 org.springframework.context.support.ClassPathXmlApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@817b38: startup date [Wed Jul 10 12:43:54 CST 2019]; root of context hierarchy
destory方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值