Lifecycle Callbacks


Execute Code after Bean Initialized

  • make Bean implement InitializingBean
  • override method public void afterPropertiesSet()
  • code is executed just after the properties have been set

Problem

  • tightly coupled to Spring Framework

Execute Code before Bean is Destroyed

  • make Bean implement DisposableBean
  • override method public void destroy()
  • code is executed just before the bean is destroyed

Problem

  • tightly coupled to Spring Framework

De-coupled Callbacks

  • write your own methods – e.g. myInit() and myDestroy()
  • configure the spring.xml and add attributes to the bean as follows:
<bean id="mybean" class="..." init-method="myInit" destroy-method="myDestroy">
...
</bean>

Common De-coupled Callbacks

  • write your own methods – e.g. myInit() and myDestroy()
  • configure the spring.xml and add attributes as follows:
<beans default-init-method="myInit" default-destroy-method="myDestroy">
<bean id="mybean" class="...">
...
</bean>
...
</beans>
  • Spring will try and run the default-init-method and default-destroy-method for every bean it configures.
  • if Spring finds the myInit() method or the myDestroy() method, then it will run it, otherwise it will ignore it
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s