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

http://static.springsource.org/spring/docs/2.0.x/reference/beans.html
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.

你可能感兴趣的:(spring)