南郭之家
南郭大侠的blog ^_^

Using Spring init and destroy lifecycle callback in non-web apps

March 15th, 2010 by Titan

When using spring to create singleton classes, we often have to use some initialing and teardown mechanisms to acquiring and releasing resources in the program, such as opening and closing files, using connections to databases, etc.

As spring recommends default constructor to ensure the testability of your class, it is necessary to use an init method and teardown method in the class. Although spring provides serveral interfaces(such as InitializingBean and DisposableBean) for programmers to implement, it is to intrusive for a program to couple with spring when a simple init method is introduced.

So spring provides XML-based configuration for this. You only have to declare the init and teardown method in bean definition in xml configuration file, such as
`` and I define init and cleanup method in HelloWorld class, it will invoked by spring automatically. Only one thing to remind, if you use destroy-method configuration in non-web apps, you have to manually invoke `((AbstractApplicationContext)context).registerShutdownHook();` to register shutdown hook after the context is created. Otherwise, the destroy-method will not be invoked by spring.

And spring also provides default-init-method=”" and default-destroy-method=”" on beans node, which will be invoked if specified method is available.

Posted in 技术

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.