Spring学习之bean的实例化,销毁
来源:互联网 发布:终端查看数据库 编辑:程序博客网 时间:2024/06/02 01:12
1.Bean的实例化
1) 指定初始化方法 使用init-method属性
在类中定义初始化的方法(名字任意)例如:init() ,在spring 配置文件中定义bean 的时候注册
<bean id ="" class ="" init-method="init">
使用init-method属性指定方法在Bean的全部依赖关系结束之后自动执行
2)实现initlializingBean 接口
存在org.springframework.beans.factory.InitializingBean中,原理:容器设置好Bean的所有必要属性后给Bean发通知,以执行初始化工作,某个Bean实例实现了InitializingBean接口,该Bean的代码就与Spring耦合到一起(不推荐使用)
例如:
public class simpleBean implements InitializingBean{ }
实现接口之后,就不需要init()方法,改为实现InitializingBean接口的afterPropertiesSet()方法 。配置文件中也不需要init-method属性,当Bean中的所有依赖关系被设置完成后Spring容器会自动调用该Bean的afterPropertiesSet()方法
2.Bean的销毁
1)使用destroy-method属性
对于基于Web的ApplicationContext实现,已有相应的代码来保证关闭应用程序时,恰当的关闭Spring容器
不是Web的应用环境下,希望容器关闭,并在关闭前用singleton的单例配置销毁回调方法,需要在JVM中注册一个关闭钩子(shutdown hook)
为注册shutdown hook 需调用AbstractApplicationContext中的registerShutdownHook()方法 ,则程序会退出springApplicationContext容器,并关闭前,调用bean的析构回调方法
在类中定义方法,方法名任意,在配置文件中添加destory-method 属性指向方法名即可,
2) 实现DisposableBean接口 ,org.springframework,beans.factory.DisposableBean接口
定义类继承DisposableBean接口,然后继承接口的void destory()方法 ,编写方法体, spring的配置文件中也不用加destory-method属性(建议使用)
- Spring学习之bean的实例化,销毁
- Spring学习笔记之Bean的实例化
- Spring学习之实例化bean的三种方式
- Spring Bean的实例化(学习笔记)
- Spring学习之使用关闭钩子销毁bean
- Spring源码解析之bean的创建和销毁
- spring学习----bean实例化
- Spring之实例化Bean
- 2--spring bean 的作用域scope 设置;bean的初始化和销毁方法,profile配置不同环境实例化不同的bean,自定义事件,自定义监听器
- Spring学习笔记-Bean初始化&销毁
- SPRING BEAN的实例化
- spring Bean的实例化
- Spring的Bean实例化
- Spring-Bean的实例化
- Spring的《XML显式装配bean》之Bean的创建与销毁操作
- Spring系列--bean容器的实例化之构造器创建bean实例(采用dtd约束)
- 实例化,执行,初始化,销毁bean对象
- Spring bean的初始化和销毁
- Tex中的表格列的宽度控制
- react-redux基础
- 杭电暑期多校集训—Regular polygon
- SQL Server CONVERT() 函数
- Leetcode85. Maximal Rectangle.
- Spring学习之bean的实例化,销毁
- PAT1060. 爱丁顿数
- 分组背包问题
- 静态变量和实例变量的区别
- MySQL中的字符串连接方法
- Codeforces Round #398(Div. 2)C. Garland
- 【51Nod1060】最复杂的数
- 仿QQ空间头部下拉放大控件
- POJ-1905(二分+计算几何)