Spring学习笔记(一)

来源:互联网 发布:linux sh 函数 编辑:程序博客网 时间:2024/06/13 17:10

记录下学习Spring是遇到的一些疑问和需要注意的地方,欢迎补充和指出错误。

关于init方法和destroy方法:

一共有三种方式使用:

1. 默认的int方法和destroy方法,通过在config文件中的beans标签下配置default-init-method和default-destroy-method属性,bean在初始化和销毁时便会执行默认的方法;

<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-init-method="init" default-destroy-method="destroy">


2.在bean标签下配置init-method和destroy-method,在该bean初始化和销毁时便会执行对应的方法;

<bean class="com.beans.Foo2" id="foo2" scope="singleton" init-method="start" destroy-method="shutdown"><property name="foo" ref="foo"></property></bean>

3.在Bean类中实现InitializingBean和DisposableBean接口,并添加相应的方法后,在初始化或销毁该Bean时便会执行对应的方法。

public class Foo2 implements InitializingBean, DisposableBean{@Overridepublic void destroy() throws Exception {// TODO Auto-generated method stub}@Overridepublic void afterPropertiesSet() throws Exception {// TODO Auto-generated method stub}}

使用第一种方法时,即使在Bean类中不存在对应的init和destroy方法,控制台也不会报错;而是用第二种方法配置时,若在Bean文件中不存在对应的方法,会报出BeanCreationException异常。

当三种方法同时应用时,第一种方法不会执行,而第二种方法会先于第三种方法执行。

需要注意的是,如果bean的生命周期设置为prototype,那么在每一个bean的初始化时init方法都会执行,而不会执行destroy方法;只有在生命周期设置为singleton,即默认情况的情况下,才会执行destroy方法(参考http://www.cnblogs.com/xing901022/p/4248122.html)。

原创粉丝点击