七、spring生命周期之初始化和销毁方法
一、通过@Bean指定初始化和销毁方法
在以往的xml中,我们是这样配置的
<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init" destroy-method="cleanup"/>
那如果采用注解 的方式该如何配置呢?
首先我们创建一个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..."); // 销毁方法
}
}
我们需要通过配置类将这个Car注册进容器中,当然这很简单。
@Configuration
public class MainConfigOfLifeCycle {
//@Scope("prototype")
@Scope("singleton") // 默认即单例
@Bean(initMethod="init",destroyMethod="detory")
public Car car(){
return new Car();
}
}
这样就搞定了,在ioc容器启动的时候,将会把Car这个类加载进容器创建其单例对象。
那我们主要是观察其初始化和销毁方法
测试方法:
@Test
public void test01(){
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//applicationContext.getBean("car");
//关闭容器
applicationContext.close();
}
打印其输出,
car constructor...
car ... init...
容器创建完成...
cat...destroy...
小结: bean的生命周期:bean创建---初始化----销毁的过程,
容器管理bean的生命周期;
我们可以自定义初始化和销毁方法;
容器在bean进行到当前生命周期的时候来调用我们自定义的初始化和销毁方法
观察上面的结果,也可以发现,在单例模式下,容器启动时则创建单例的car对象,并调用其初始化方法init,当容器要关闭时,执行其销毁方法destroy。
在多例模式下,这里没测,多例模式下,当我们主动获取对象的时候,容器才会创建bean,类似于一种懒加载机制,另外,在多例模式下,我们观察不到销毁方法的执行,因为多例模式下,spring的ioc不再管理我们自定义的销毁方法。
二、实现InitializingBean,DisposableBean定义初始化和销毁方法
InitializingBean
接口只有一个抽象方法:
void afterPropertiesSet() throws Exception;
DisposableBean
接口也只有一个抽象方法
void destroy() throws Exception;
我们写一个普通类继承这两个接口 ,
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
@Component
public class Cat implements InitializingBean,DisposableBean {
public Cat(){
System.out.println("cat constructor...");
}
@Override
public void destroy() throws Exception {
System.out.println("cat...destroy...");
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("cat...afterPropertiesSet...");
}
}
编写一个测试方法,启动ioc容器,测试它的生命周期
@Test
public void test01(){
//1、创建ioc容器
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfLifeCycle.class);
System.out.println("容器创建完成...");
//applicationContext.getBean("car");
//关闭容器
applicationContext.close();
}
控制台打印:
cat constructor...
cat...afterPropertiesSet...
容器创建完成...
cat...destroy...
从方法名就能看出,在cat这个对象的的属性都被注入之后,就会调用afterPropertiesSet
这个方法
再容器销毁前,会调用Cat
类的destroy方法。
三、通过@PostConstruct和@PreDestroy
这两个是JSR250规范中的,标注在方法上,也是在对象创建完成属性赋值之后,同样也是在容器销毁之前@PreDestroy标注的方法会被调用
我们也来举例测试一下,
创建一个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...");
}
}
依旧使用上面的测试方法进行测试
输出结果如下
dog constructor...
Dog....@PostConstruct...
容器创建完成...
Dog....@PreDestroy...
四、 小结
以上我们介绍了三种方法对容器中的对象进行初始化和销毁,这只是spring容器中bean生命周期的一小小部分。
这三种方法可以组合进行使用,即Combining lifecycle mechanisms
当组合使用时,那这三种方法的执行顺序是什么呢?
我们不再测试,直接看spring官方文档:
Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, are called as follows:
初始化顺序
- Methods annotated with
@PostConstruct
afterPropertiesSet()
as defined by theInitializingBean
callback interface- A custom configured
init()
method
Destroy methods are called in the same order:
销毁顺序:
- Methods annotated with
@PreDestroy
destroy()
as defined by theDisposableBean
callback interface- A custom configured
destroy()
method
七、spring生命周期之初始化和销毁方法的更多相关文章
- 生命周期(初始化、销毁方法、BeanPostProcessor后处理Bean)
1.初始化和销毁 在目标方法执行前后进行初始化或销毁 (1)在Service方法的实现类里面创建初始化方法和销毁方法: public class StudentServiceImpl implemen ...
- Spring的几种初始化和销毁方法
一 指定初始化和销毁方法 通过@Bean指定init-method和destroy-method: @Bean(initMethod="init",destroyMethod=&q ...
- Spring学习笔记之初始化和销毁方法的调用次序
Multiple lifecycle mechanisms configured for the same bean, with different initialization methods, a ...
- 12、生命周期-@Bean指定初始化和销毁方法
12.生命周期-@Bean指定初始化和销毁方法 Bean的生命周期:创建->初始化->销毁 容器管理bean的生命周期 我们可以自定义初始方法和销毁方法,容器在bean进行到当期那生命周期 ...
- 说下spring生命周期
面试官:说下spring生命周期 程序员:不会 那你先回去等消息吧 Bean实现了BeanNameAware,Spring会将Bean的ID透传给setBeanName java.后端开发.程 ...
- Spring生命周期详解
导读 Spring中Bean的生命周期从容器的启动到停止,涉及到的源码主要是在org.springframework.context.support.AbstractApplicationContex ...
- Spring学习总结(4)-Spring生命周期的回调
参考文档:https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/core.html#beans ...
- 【源码】spring生命周期
一.spring生命周期 1. 实例化Bean 对于BeanFactory容器,当客户向容器请求一个尚未初始化的bean时,或初始化bean的时候需要注入另一个尚未初始化的依赖时,容器就会调用crea ...
- spring通过注解注册bean的方式+spring生命周期
spring容器通过注解注册bean的方式 @ComponentScan + 组件标注注解 (@Component/@Service...) @ComponentScan(value = " ...
随机推荐
- SQL SERVER错误:已超过了锁请求超时时段。
问题:远程连接数据库,无法打开视图,报错:SQL SERVER错误:已超过了锁请求超时时段. (Microsoft SQL Server,错误: 1222) 执行语句获取进程id select * f ...
- Function函数的声明方式
函数 函数是一段可以反复利用的代码 Function函数的声明方式, +通过变量,把函数存储到变量容器里 var a=function(){ console.log("大瓜皮") ...
- 洛谷P2029跳舞
题目 DP, 用的\(dp[i][j]\)表示\(i\)之前的数选了\(j\)个得到的最大结果,然后状态转移方程应该是 \[if (j \% t == 0)~~dp[i][j] = max(dp[i] ...
- ajax post data 获取不到数据,注意 content-type的设置 、post/get(转)
ajax post data 获取不到数据,注意 content-type的设置 .post/get 关于 jQuery data 传递数据.网上各种获取不到数据,乱码之类的. 好吧今天我也遇到了 ...
- hdoj - 1342 Lotto
Problem Description In a Lotto I have ever played, one has to select 6 numbers from the set {1,2,... ...
- Ubuntu 16.04与Win10双系统双硬盘安装图解
一.先做准备工作.建议:在当前系统所在的硬盘上,留一片空的主分区安装Ubuntu系统. 2.划分多大的空间够?安装的过程中需要涉及到分区,为了以免日后重装,我的建议是如下分区:1).5G,主分区,空间 ...
- Cesium学习笔记-工具篇20-PrimitiveTexture自定义渲染-贴图【转】
前几篇博客我们了解了自定义点.线.面绘制,这篇我们接着学习cesium自定义纹理贴图.我们完成点线面的绘制,只是绘制出了对象的框架,没有逼真的外观.逼真外观是需要设置材质来实现:Material . ...
- 时针分针角度问题c语言解法
#include <stdio.h> //时针一小时走30度 double hour_per_hour_angle = 30.0; //先算出时针和分钟 一分钟内 分别走多少度数 //时针 ...
- MySQL事务隔离级别(一)
本文实验的测试环境:Windows 10+cmd+MySQL5.6.36+InnoDB 一.事务的基本要素(ACID) 1.原子性(Atomicity):事务开始后所有操作,要么全部做完,要么全部不做 ...
- Join Reorder优化 - 论文摘要
Query Simplification: Graceful Degradation for Join-Order Optimization 这篇的related work可以参考,列的比较全面, Q ...