Ebooks

Spring Boot @PostConstruct

Spring Boot @PostConstruct tutorial shows how to use the @PostConstruct annotation in a Spring application.

Spring is a popular Java application framework and Spring Boot is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily.

@PostConstruct

@PostConstruct is an annotation used on a method that needs to be executed after dependency injection is done to perform any initialization.

Spring Boot @PostConstruct example

The following application demonstrates the usage of @PostConstruct. It uses the annotation to create two log methods that are called after their beans are initialized. These messages are shown after the application is run. The application itself sends a message to the client. The text message is read from a configuration file.

$ tree
.
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   └── com
    │   │       └── zetcode
    │   │           ├── Application.java
    │   │           ├── controller
    │   │           │   └── MyController.java
    │   │           └── service
    │   │               ├── IMessageService.java
    │   │               └── MessageService.java
    │   └── resources
    │       ├── application.properties
    │       └── static
    │           └── index.html
    └── test
        └── java

This is the project structure.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" 
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd">
    
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zetcode</groupId>
    <artifactId>SpringBootPostConstruct</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
    </parent>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>   
        
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>          
    
</project>

This is the Maven pom.xml file. The spring-boot-starter-parent is a parent POM providing dependency and plugin management for applications built with Maven. The spring-boot-starter-web is a starter for building web, including RESTful, applications using Spring MVC. It uses Tomcat as the default embedded container. The spring-boot-maven-plugin packages Spring applications into executable JAR or WAR archives.

application.properties
my.msg=Hello there

spring.main.banner-mode=off
logging.level.org.springframework=ERROR

The application.properties is the main configuration file in Spring Boot. We set a message property, which will be returned by the application to the client. We turn off the Spring banner and reduce the amount of logging of the Spring framework.

MyController.java
package com.zetcode.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.zetcode.service.IMessageService;
import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestController
public class MyController {

    private static final Logger logger = LoggerFactory.getLogger(MyController.class);

    @Autowired
    IMessageService messageService;

    @RequestMapping(value = "/getMessage")
    public String getMessage() {

        String message = messageService.getMessage();

        return message;
    }

    @PostConstruct
    public void doLog() {
        logger.info("Info message in MyController");
    }
}

This is MyController. It sends a message to the client.

@RequestMapping(value = "/getMessage")
public String getMessage() {

    String message = messageService.getMessage();

    return message;
}

A message is generated from the message service and returned to the client.

@PostConstruct
public void doLog() {
    logger.info("Info message in MyController");
}

The doLog() method is decorated with the @PostConstruct annotation. The method is called after the MyController bean is initialized. It logs a simple informational message.

IMessageService.java
package com.zetcode.service;

public interface IMessageService {

    public String getMessage();
}

The IMessageService contains the getMessage() contract method.

MessageService.java
package com.zetcode.service;

import javax.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class MessageService implements IMessageService {

    private static final Logger logger = LoggerFactory.getLogger(MessageService.class);

    @Value(value = "${my.msg}")
    private String message;

    @Override
    public String getMessage() {

        return message;
    }

    @PostConstruct
    public void doLog() {
        logger.info("Info message in MessageService");
    }
}

The MessageService contains the implementation of the getMessage() method.

@Value(value = "${my.msg}")
private String message;

The message that is returned to the client is read from the application.properties file with the @Value annotation and set to the message field.

@Override
public String getMessage() {

    return message;
}

The getMessage() returns the message string.

@PostConstruct
public void doLog() {
    logger.info("Info message in MessageService");
}

MessageService also contains the doLog() method decorated with @PostConstruct. It is called after the bean is initialized.

index.html
<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <p>
            <a href="getMessage">Get Message</a>
        </p>
    </body>
</html>

This is the home page. It contains a link to get the message.

Application.java
package com.zetcode;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application  {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Application is the entry point which sets up Spring Boot application. The @SpringBootApplication annotation enables auto-configuration and component scanning.

$ mvn -q spring-boot:run 
...
2017-12-14 21:35:30.788  INFO 10665 --- [main] com.zetcode.service.MessageService  : Info message in MessageService
2017-12-14 21:35:30.791  INFO 10665 --- [main] com.zetcode.controller.MyController : Info message in MyController
...

After the application is run, we can see these two log messages on the console.

In this tutorial, we have shown how to use @PostConstruct annotation in a Spring application. You might also be interested in the related tutorials: Java Servlets tutorial, Spring Boot @Controller tutorial, Spring Boot @ExceptionHandler tutorial, Spring Boot upload file, Spring Boot @PathVariable tutorial, Spring Boot @RequestParam tutorial, Spring Boot @ResponseBody tutorial, Java tutorial.