Announcement Announcement Module
No announcement yet.
How to ensure a bean is destoryed? Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to ensure a bean is destoryed?

    I want to ensure some bean created resource to be clean up gracefully (e.g. unlock the locked files).

    Can I do like this?

    1. Specify destroy method in the bean config.
    2. Ensure we call applicationContext.close() before the program exit.

    If I can do like this, how should we handle if I got exception during the destroy method is executed?

  • #2
    Any exceptions that would be thrown would have to be run-time exceptions, and really I would implement the error handling directly in the destroy method to try and do its best to recover from that exception.

    In fact, you may want to put some cleanup in your startup routines as well, because these lifecycle related calls are only going to happen during graceful shutdown activities. In the case of a power hit to the box and a hard shutdown, the state of resources wouldn't be guarunteed by Spring. For example, if your application wants to write something to the end of a file every time it shuts down, it may not get that opportunity (coincidentally, that would be an argument for a database if you want ACID like properties and recovery procedures).

    It would also be good to research whatever OS level resource management is present for the resources you want. For example on Linux, locks are associated with a process, and if that process dies the lock will get cleaned up. I'm not sure how it's handled on Windows.


    • #3
      You specify the destroy method tag on the bean definition

      <bean id="myBean" class="a.b.c.MyClass" destroy-method="close">
      Personally, I think you should never thrown exception out of this method, catch and handle all exceptions, including runtime, inside that method.