springboot学习:bean生命周期

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/lw305993897/article/details/102755745

1、bean 生命周期

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

2、自定义初始化方法和销毁方法

2.1、通过@Bean指定初始化方法(initMethod)和销毁方法(destroyMethod)

  • MainConfigLifeCycle类
@Configuration
public class MainConfigLifeCycle {
	@Bean(initMethod = "init", destroyMethod = "destroy")
	public Car car() {
		return new Car();
	}
}
  • Car类
public class Car {
	public Car() {
		System.out.println("new car");
	}
	public void init() {
		System.out.println("car init");
	}
	public void destroy() {
		System.out.println("car destroy");
	}
}
  • IOCTest_LifeCycle类
@Test
public void test1() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
	System.out.println("容器初始化");
	context.close();
}

在这里插入图片描述

2.2、通过让bean实现InitializingBean接口(定义初始化接口),DisposableBean接口(销毁接口)

  • Cat类
@Component
public class Cat implements InitializingBean,DisposableBean {
	public Cat() {
		System.out.println("new cat");
	}
	public void destroy() throws Exception {
		System.out.println("cat destroy");
	}
	public void afterPropertiesSet() throws Exception {
		System.out.println("cat afterPropertiesSet");
	}
}
  • MainConfigLifeCycle类
@ComponentScan("com.dav.bean")
@Configuration
public class MainConfigLifeCycle {
}
  • IOCTest_LifeCycle类
@Test
public void test1() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
	System.out.println("容器初始化");
	context.close();
}

在这里插入图片描述

2.3、使用JAVA的JSR250注解

@PostConstruct:在bean创建完成并且属性赋值完成;来执行初始化方法;
@PreDestroy:在容器销毁bean之前通知我们进行清理工作;

  • Dog类
@Component
public class Dog {
	public Dog() {
		System.out.println("new dog");
	}
	@PostConstruct
	public void init() {
		System.out.println("dog @PostConstruct");
	}
	@PreDestroy
	public void destroy() {
		System.out.println("dog @PreDestroy");
	}
}
  • MainConfigLifeCycle类
@ComponentScan("com.dav.bean")
@Configuration
public class MainConfigLifeCycle {
}
  • IOCTest_LifeCycle类
@Test
public void test1() {
	AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigLifeCycle.class);
	System.out.println("容器初始化");
	context.close();
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/lw305993897/article/details/102755745