Spring注解系列十三:生命周期-@PostConstruct和@PreDestroy

1、MainConfigOfLifeCycle

/**
 * 3)、可以使用JSR250;
 * 		@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法
 * 		@PreDestroy:在容器销毁bean之前通知我们进行清理工作
 */
@ComponentScan("com.atguigu.bean")
@Configuration
public class MainConfigOfLifeCycle {

}

2、创建类Dog

@Component
public class Dog {
	
	public Dog(){
		System.out.println("dog constructor...");
	}
	
	//对象创建并赋值之后调用
	@PostConstruct
	public void init(){
		System.out.println("Dog....@PostConstruct...");
	}
	
	//容器移除对象之前
	@PreDestroy
	public void detory(){
		System.out.println("Dog....@PreDestroy...");
	}

}

3、测试

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

在这里插入图片描述

猜你喜欢

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