liveBook · Manning

@PostConstruct

As explained in Spring Start Here, Second Edition

An annotation that marks a method to be invoked after dependency injection is complete and before the managed object is put into service.

@PostConstruct marks a method for Spring to call after a bean’s constructor finishes. Use it to set initial state when Spring creates a component. section 2.2

@Component
public class Parrot {
 
  private String name;
 
  @PostConstruct
  public void init() {
    this.name = "Kiki";
  }
 
  // Omitted code
}

The Parrot component’s init method sets its name to “Kiki”; Spring invokes the annotated method after construction. section 2.2

The annotation comes from Jakarta EE; a Maven application needs the jakarta.annotation-api dependency to use it. section 2.2

How Spring Start Here, Second Edition covers it

How deep it goes
Defines an annotated callback method and its timing after constructor completion, without detailing further lifecycle ordering.
Examples
Initializes a Parrot component’s name to “Kiki” in an init method.
What it assumes
Uses a Spring-managed component; the example demonstrates the annotation within a Parrot class.
What you can do after
Apply it by annotating a component method that initializes the bean after construction.
How it connects
Connects bean lifecycle callbacks with Spring beans and stereotype annotations such as @Component.

Also explained in

Compare how 2 books explain @PostConstruct →

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.