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属性(建议使用)