DEV Community

realNameHidden
realNameHidden

Posted on

2 1 1 1 1

@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);
    }
}

Enter fullscreen mode Exit fullscreen mode

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");
    }
}

Enter fullscreen mode Exit fullscreen mode

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

Constructor: ExampleBean is created
PostConstruct: ExampleBean is initialized

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (1)

Collapse
 
boma086 profile image
boma086

what is @PreConstruct?

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay