生命周期(一)--@Bean指定初始化和销毁方法

bean的生命周期:
    bean创建—初始化----销毁的过程
容器管理bean的生命周期;
我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法

指定初始化和销毁方法;
    在bean.xml中可以指定init-method和destroy-method
    通过@Bean指定init-method和destroy-method;
首先我们创建一个Car.java,里边除了Car的构造器,添加初始化和销毁方法

import org.springframework.stereotype.Component;
@Component
public class Car {
	
	public Car(){
		System.out.println("car constructor...");
	}
	
	public void init(){
		System.out.println("car ... init...");
	}
	
	public void detory(){
		System.out.println("car ... destory...");
	}

}

创建MainConfigOfLifeCycle.java配置类,@Bean给容器中添加组件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MainConfigOfLifeCycle {
	
	//@Scope("prototype")
	@Bean(initMethod="init",destroyMethod="detory")
	public Car car(){
		return new Car();
	}
}

测试类IOCTest_LifeCycle.java中创建容器,查看bean的创建销毁

import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.atguigu.config.MainConfigOfLifeCycle;

public class IOCTest_LifeCycle {
	
	@Test
	public void test01(){
		//1、创建ioc容器
		AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
		System.out.println("容器创建完成...");
		
		//applicationContext.getBean("car");
		//关闭容器
		System.out.println("容器进行关闭...");
		applicationContext.close();
	}
}

运行结果如下图,容器创建完成之前就注册了组件并进行了初始化,关闭容器的时候销毁bean
在这里插入图片描述
但是如果在注册多实例Bean,则只有在bean调用的时候才会创建Bean,而且并不会在容器关闭的时候销毁Bean,需要我们自行调用销毁方法进行销毁
在这里插入图片描述

总结:
构造(对象创建)
    单实例:在容器启动的时候创建对象
    多实例:在每次获取的时候创建对象
初始化:
    对象创建完成,并赋值好,调用初始化方法。。。
销毁:
    单实例:容器关闭的时候
    多实例:容器不会管理这个bean;容器不会调用销毁方法;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值