Categories
Java

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
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd"
        default-lazy-init="true"
        default-init-method="defaultInit"
        default-destroy-method="defaultDestroy" >
    
    	<context:annotation-config/>
    
        <bean id="simpleBean" class="eu.lucazanini.mybean.SimpleBean" 
    	scope="singleton" />
    
    </beans>
    

    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
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration PUBLIC "-//LOGGER" "log4j.dtd">
    
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> 
        <appender name="stdout" class="org.apache.log4j.ConsoleAppender">
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" />
    <!--
    ConversionPattern format specification
    %d      inserts the date; you can specify the format (%d{yyyy-MM-dd HH:mm:ss,SSS})
    %-5p    inserts the priority log level, 5 characters, left justified
    %c{1}   inserts the name of the class
    %L      inserts the line number
    %m      inserts the user message
    %n      inserts the separator (for example, a new line)
    -->
            </layout>
        </appender>
    
        <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
        	<param name="append" value="false" />
            <param name="Threshold" value="DEBUG" />
            <param name="File" value="logs/app.log"/>
            <param name="MaxFileSize" value="512KB" />
            <param name="MaxBackupIndex" value="10" />
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%d %-5p %c{1}:%L %m %n" />
            </layout>
        </appender>
    
    <!--sets the priority log level for org.springframework-->
        <logger name="org.springframework">
            <level value="info"/>
        </logger>
    
    <!--sets the priority log level for eu.lucazanini-->
        <logger name= "eu.lucazanini">
            <level value="debug"/>
        </logger>
    
    <!--sets the default priority log level-->
        <root>
            <priority value="debug"></priority>
            <appender-ref ref="stdout"/>
            <appender-ref ref="fileAppender"/>
        </root>
    </log4j:configuration>
    
  3. create the file eu/lucazanini/mybean/Main.java
    package eu.lucazanini.mybean;
    
    import org.apache.log4j.Logger;
    import org.springframework.context.support.*;
    
    public class Main {
    
        private static org.apache.log4j.Logger log = Logger.getLogger(Main.class);
    
        public static void main(String[] args) {
    
    	GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
    	ctx.load("classpath:app-context.xml");
    	ctx.refresh();
    
    	log.debug("creating bean");
    	SimpleBean bean = (SimpleBean) ctx.getBean("simpleBean");
    	log.debug("created bean");
    
    	log.debug("destroying bean");
    	ctx.destroy();
    	
    	log.debug("destroyed bean");
    
    	log.debug("application shutdown");
        }
    }
    
  4. create the file eu/lucazanini/mybean/SimpleBean.java
    package eu.lucazanini.mybean;
    
    import org.apache.log4j.Logger;
    
    public class SimpleBean {
    
        private static org.apache.log4j.Logger log = Logger
    	    .getLogger(SimpleBean.class);
    
        public SimpleBean() {
    	log.debug("constructor");
        }
    
        public void defaultInit() {
    	log.debug("defaultInit-method");
        }
    
        public void defaultDestroy() {
    	log.debug("defaultDestroy-method");
        }
    
    }
    

    where the default methods are highlighted

The output is the following:

...
DEBUG Main:[...] creating bean 
DEBUG SimpleBean:[...] constructor 
DEBUG SimpleBean:[...] defaultInit-method 
DEBUG Main:[...] created bean 
DEBUG Main:[...] destroying bean 
...
DEBUG SimpleBean:[...] defaultDestroy-method 
DEBUG Main:[...] destroyed bean 
DEBUG Main:[...] application shutdown 

Leave a Reply

Your email address will not be published.

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