This tutorial will show you how we can use @PostConstruct and @PreDestroy in Spring. @PostConstruct and @PreDestroy annotations are generally considered best practice for receiving lifecycle callbacks in a modern Spring application. Using these annotations means that our beans are not coupled to Spring specific interfaces. For more information please refer to

Sometimes we need to load some data or perform initialization work after all necessary properties on the bean have been set by the container. In this example we will load data from database during application startup and set that value to a System property so that the value will be set only once and that value can be used later after retrieving from the System property.
For this tutorial we will create a standalone maven project in Eclipse. If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.

The following configurations are required in order to run the application
Eclipse Kepler
JDK 1.7
Have maven installed and configured
Spring dependencies in pom.xml
Now we will see the below steps how to create a maven based spring project in Eclipse
Step 1. Create a standalone maven project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

Now enter the required fields (Group Id, Artifact Id) as shown below
Group Id : com.roytuts
Artifact Id : spring-postconstruct-predestroy
Step 2. Modify the pom.xml file as shown below.

<project xmlns="" xmlns:xsi=""
        <!-- Spring framework -->
        <!-- mysql driver -->
        <!-- junit -->

Step 3. If you see JRE System Library[J2SE-1.4] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.4], click on Edit button and select the appropriate jdk 1.8 from the next window. Click on Finish then Ok.

Step 4. Create src/main/resources folder for putting the resource files.
Do right-click on the project and go New -> Source Folder. Give Folder name: as src/main/resources and click on Finish button.
Step 5. Create an XML file under src/main/resources.

Do right-click on src/main/resources in the project and go New -> file. Give File name: as spring-postconstruct-predestroy-properties.xml and click on Finish button.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi="" xmlns:p=""
    xmlns:aop="" xmlns:context=""
    xmlns:jee="" xmlns:tx=""
    <bean id="jdbcProperties"
        <property name="order" value="99999" />
        <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
        <property name="ignoreUnresolvablePlaceholders" value="true" />
        <property name="properties">

Step 6. Create spring-postconstruct-predestroy-datasource.xml file under src/main/resources with the below content.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
    xmlns:xsi="" xmlns:p=""
    xmlns:aop="" xmlns:context=""
    xmlns:jee="" xmlns:tx=""
    <import resource="spring-postconstruct-predestroy-properties.xml" />
    <bean id="dataSource"
        <property name="driverClassName" value="${JDBC.DRIVER}" />
        <property name="url" value="${JDBC.URL}" />
        <property name="username" value="${JDBC.USERNAME}" />
        <property name="password" value="${JDBC.PASSWORD}" />
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    <bean id="flagDAO" class="com.roytuts.spring.dao.impl.FlagDAOImpl" />

Step 7. Create a MySQL table

  `flag_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `flag_val` varchar(30) NOT NULL,
  PRIMARY KEY (`flag_id`)

Step 8. Create a POJO class for flag.

package com.roytuts.spring.dto;
public class Flag {
    private Integer flagId;
    private String flagVal;
    public Flag() {
    public Flag(Integer flagId, String flagVal) {
        this.flagId = flagId;
        this.flagVal = flagVal;
    public Integer getFlagId() {
        return flagId;
    public void setFlagId(Integer flagId) {
        this.flagId = flagId;
    public String getFlagVal() {
        return flagVal;
    public void setFlagVal(String flagVal) {
        this.flagVal = flagVal;

Step 9. Create a DAO in com.roytuts.spring.dao package

package com.roytuts.spring.dao;
import java.util.List;
import com.roytuts.spring.dto.Flag;
public interface FlagDAO {
    void selectFlag();

Note : if you get error then you can change the Compiler compliance level, Generated .class files compatibility, Source compatibility to 1.7

Step 10. Now create a DAO implementation class in com.roytuts.spring.dao.impl package.

package com.roytuts.spring.dao.impl;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import com.roytuts.spring.dao.FlagDAO;
import com.roytuts.spring.dto.Flag;
public class FlagDAOImpl implements FlagDAO {
    private JdbcTemplate jdbcTemplate;
    private final String SQL_SELECT_FLAG_VAL = "select flag_val from flag where flag_id = 1";
    @PostConstruct // do some initialization work
    public void selectFlag() {
        String val = jdbcTemplate.queryForObject(SQL_SELECT_FLAG_VAL, null, String.class);
    @PreDestroy // do some destruction work (like releasing pooled connections)
    public void cleanFlag() {
        System.setProperty("dbFlag", null);
    private void setDbFlag(String dbFlag) {
        System.setProperty("dbFlag", dbFlag);
        System.out.println("DB Flag : " + System.getProperty("dbFlag"));

Step 11. Create JUnit test case under src/test/java folder.

package com.roytuts.spring.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import com.roytuts.spring.dto.Flag;
public class FlagDAOImplTest {
    private FlagDAO flagDAO;
    public void setUp() {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-postconstruct-predestroy-datasource.xml");
        flagDAO = (FlagDAO) applicationContext.getBean("flagDAO");
    public void selectFlagTest() {

Step 12. Run the above JUnit test case.

Step 13. Now Look at the console log. You will see that during startup the flag value is fetched from database.


Leave a Reply

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