ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

springboot学习:bean生命周期

2019-10-26 14:07:27  阅读:173  来源: 互联网

标签:生命周期 springboot MainConfigLifeCycle void System bean println public out


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();
}

在这里插入图片描述

标签:生命周期,springboot,MainConfigLifeCycle,void,System,bean,println,public,out
来源: https://blog.csdn.net/lw305993897/article/details/102755745

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有