Logo

dev-resources.site

for different kinds of informations.

@PreConstruct and @PostConstruct annotation Spring Boot Example

Published at
1/5/2025
Categories
java
interview
spring
boot
Author
realNameHidden
Categories
4 categories in total
java
open
interview
open
spring
open
boot
open
@PreConstruct and @PostConstruct annotation Spring Boot Example

@PostConstruct: This method is called after the Spring bean (in this case, ExampleBean) has been created and all dependencies have been injected. It’s an ideal place to put initialization logic.

@PreDestroy: This method is called before the Spring bean is destroyed. It’s where you can place cleanup logic, such as closing resources.
Create Spring Boot Application

DemoApplication

package com.example.demo;

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

@SpringBootApplication
public class DemoApplication {

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

ExampleBean

package com.example.demo;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Component
public class ExampleBean {

    public ExampleBean() {
        System.out.println("Constructor: ExampleBean is created");
    }

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct: ExampleBean is initialized");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("PreDestroy: ExampleBean is about to be destroyed");
    }
}

When you run this Spring Boot application, you should see output similar to the following:

Constructor: ExampleBean is created
PostConstruct: ExampleBean is initialized

This output shows that the constructor runs first, followed by the @PostConstruct method.

When you stop the application (e.g., by pressing Ctrl + C if running in the terminal), the @PreDestroy method will be called:

PreDestroy: ExampleBean is about to be destroyed

Featured ones: