spring的init-method和destroy-method方法使用

[url]http://static.springsource.org/spring/docs/2.0.x/reference/beans.html[/url]
3.5.1.2. Destruction callbacks
<bean id="datasource"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="$[]" />
</bean>
destroy-method指定了當要銷燬bean datasource之前要做的操作,也就是這個bean的收尾工作。
這裏是指定了close()方法。
Closes and releases all idle connections that are currently stored in the connection pool associated with this data source.
http://commons.apache.org/dbcp/apidocs/org/apache/commons/dbcp/BasicDataSource.html
也可以像下面這樣設置全局的init方法
<beans default-init-method="init">
<bean id="blogService" class="com.foo.DefaultBlogService">
<property name="blogDao" ref="blogDao" />
</bean>
</beans>

要注意的是init和interceptor一起使用的情況,當bean和intereptor分開定義時,可以繞過proxy訪問這個bean了。但是,還是不要在init裏關聯interceptor,因爲
這樣bean的生命週期會與proxy/interceptors耦合:
Finally, please be aware that the Spring container guarantees that a configured initialization callback is called immediately after a bean has been supplied with all of it's dependencies. This means that the initialization callback will be called on the raw bean reference, which means that any AOP interceptors or suchlike that will ultimately be applied to the bean will not yet be in place. A target bean is fully created first, then an AOP proxy (for example) with its interceptor chain is applied. Note that, if the target bean and the proxy are defined separately, your code can even interact to the raw target bean, bypassing the proxy. Hence, it would be very inconsistent to apply the interceptors to the init method, since that would couple the lifecycle of the target bean with its proxy/interceptors, and leave strange semantics when talking to the raw target bean directly.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章