Spring bean的初始化及销毁

Spring bean的几个属性:scopeinit-methoddestroy-methoddepends-on等。

 

Scope

在Spring容器中是指其创建的Bean对象相对于其他Bean对象的请求可见范围。

scope分类:singleton, prototype, request, session, global session。

这里的singleton和设计模式里面的单例模式不一样,标记为singleton的bean是由容器来保证这种类型的bean在同一个容器内只存在一个共享实例,而单例模式则是保证在同一个Classloader中只存在一个这种类型的实例。

 

 

init-method

是指创建bean时调用的方法,注意,不是创建bean的方法。

destroy-method

是指销毁bean时调用的方法,同样,不是销毁bean的方法。

 

注意:scope为prototype的bean,容器会将创建好的对象实例返回给请求方,之后,容器就不再拥有其引用请求方需要自己负责当前对象后继生命周期的管理工作,包括该对象的销毁

所以:scope为singleton的bean的destroy方法则是在容器关闭时执行,而scope为prototype的bean是不会执行destroy方法的。

 

depends-on

用于指定bean初始化及销毁时的顺序。注意上面的结论

<bean id="helloApi" class="cn.javass.spring.chapter2.helloworld.HelloImpl"/>
<bean id="decorator" 
class="cn.javass.spring.chapter3.bean.HelloApiDecorator" 
depends-on="helloApi">
<property name="helloApi"><ref bean="helloApi"/></property>
</bean>

“decorator”指定了“depends-on”属性为“helloApi”,所以在“decorator”Bean初始化之前要先初始化“helloApi”而在销毁“helloApi”之前先要销毁“decorator”,大家注意一下销毁顺序。

 

Spring 允许 Bean 在初始化完成以及销毁执行特定的操作。下面是常用的三种指定特定操作的方法:

    通过实现 InitializingBean / DisposableBean 接口;
    通过<bean> 元素的 init-method / destroy-method属性;
    通过@PostConstruct或@PreDestroy注解。

Bean在实例化的过程中:Constructor > @PostConstruct >InitializingBean > init-method

Bean在销毁的过程中:@PreDestroy > DisposableBean > destroy-method

 

参考:

Spring bean 的init-method和destroy-method
Spring容器中的Bean几种初始化方法和销毁方法的先后顺序
Spring scope属性详解

 

----------------------------------------------------------

可以和@Component一起使用的注解:

@Lazy(true) -- 延迟初始化

@DependsOn({"managedBean"}) --  初始化及销毁时的顺序

@Qualifier -- 见 Spring 依赖注入(DI)的注解

@Primary -- 当有多个候选时,被注解的bean作为首选项,否则异常。

 

 

 

posted on 2016-05-23 17:05  LarryZeal  阅读(11303)  评论(0编辑  收藏  举报

导航