How to set a default method to running code on the creation or destruction of a bean

In the post Executing code on the creation or destruction of a bean in Spring I explain three ways to execute code on the creation or destruction of a Bean in Spring.
With two of these ways you can set the execution of a specific custom method:

  • with the annotations @PostConstruct and @PreDestroy
  • configuring the properties init-method and destroy-method

There is a very convenient way in the case that more beans have methods with the same name to be executed on their creation and destruction, i.e. you can specify a default method for all the beans.

For example see the following java project:

  1. create the file conf/app-context.xml

    where the default methods are set in the highlighted lines;
    the folder “conf” must be in the classpath
  2. create the file conf/log4j.xml
  3. create the file eu/lucazanini/mybean/Main.java
  4. create the file eu/lucazanini/mybean/SimpleBean.java

    where the default methods are highlighted

The output is the following:

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.