Spring注解系列十一:生命周期-bean

1、MainConfigOfLifeCycle

/**
 * bean的生命周期:
 * 		bean创建---初始化----销毁的过程
 * 容器管理bean的生命周期;
 * 我们可以自定义初始化和销毁方法;容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
 * 
 * 构造(对象创建)
 * 		单实例:在容器启动的时候创建对象
 * 		多实例:在每次获取的时候创建对象
 * 
 * 初始化:
 * 		对象创建完成,并赋值好,调用初始化方法
 *
 * 销毁:
 * 		单实例:容器关闭的时候
 * 		多实例:容器不会管理这个bean;容器不会调用销毁方法;
 *
 * 1)、指定初始化和销毁方法;
 * 		通过@Bean指定initMethod和destroyMethod
 *
 */
@Configuration
public class MainConfigOfLifeCycle {
	
	@Bean(initMethod="init",destroyMethod="detory")
	public Car car(){
		return new Car();
	}

}

2、创建组件Car

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 ... detory...");
	}

}

3、测试单实例

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

}

在这里插入图片描述
4、测试多实例
(1)、添加注解@Scope(“prototype”)

@Scope("prototype")
@Bean(initMethod="init",destroyMethod="detory")
public Car car(){
	return new Car();
}

(2)、获取bean

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lizhiqiang1217/article/details/89950077