Saturday, 20 July 2019

Lifecycle callbacks in Spring

To interact with the container’s management of the bean lifecycle, you can implement
the Spring InitializingBean and DisposableBean interfaces. The container calls
afterPropertiesSet() for the former and destroy() for the latter to allow the bean to perform
certain actions upon initialization and destruction of your beans.

Initialization callbacks

It is recommended that you do not use the InitializingBean interface because it unnecessarily
couples the code to Spring.

hence use the initMethod attribute of @Bean, this will initialize the bean when invoked.

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" autowire = "constructor" scope="singleton" init-method="init" autowire-candidate="false">

</bean>

private String init() {
this.mMessage="Welcome to Search Endeca123";
HelloWorld hello=new HelloWorld();
return hello.getMessage();
}

Destruction callbacks

It is recommended that you do not use the DisposableBean callback interface because it
unnecessarily couples the code to Spring.

Hence With XML-based configuration metadata, you use the destroy-method attribute on the <bean/>

<bean id="helloWorldService"
class="com.searchendeca.application.HelloWorld" autowire = "constructor" scope="singleton" destroy-method="cleanup" autowire-candidate="false">
</bean>

private void cleanup() {
//Some Clean up
}

The presence of the default-init-method attribute on the top-level <beans/> element attribute
causes the Spring IoC container to recognize a method called init on beans as the initialization method callback.When a bean is created and assembled, if the bean class has such a method, it is invoked at the appropriate time.

No comments:
Write comments