When The Context Starts
To invoke a method when a bean is constructed, use the jakarta.annotation.PostConstruct
annotation:
import jakarta.annotation.PostConstruct; (1)
import jakarta.inject.Singleton;
@Singleton
public class V8Engine implements Engine {
private int cylinders = 8;
private boolean initialized = false; (2)
@Override
public String start() {
if (!initialized) {
throw new IllegalStateException("Engine not initialized!");
}
return "Starting V8";
}
@Override
public int getCylinders() {
return cylinders;
}
public boolean isInitialized() {
return initialized;
}
@PostConstruct (3)
public void initialize() {
initialized = true;
}
}
import jakarta.annotation.PostConstruct (1)
import jakarta.inject.Singleton
@Singleton
class V8Engine implements Engine {
int cylinders = 8
boolean initialized = false (2)
@Override
String start() {
if (!initialized) {
throw new IllegalStateException("Engine not initialized!")
}
return "Starting V8"
}
@PostConstruct (3)
void initialize() {
initialized = true
}
}
import jakarta.annotation.PostConstruct
import jakarta.inject.Singleton
@Singleton
class V8Engine : Engine {
override val cylinders = 8
var initialized = false
private set (2)
override fun start(): String {
check(initialized) { "Engine not initialized!" }
return "Starting V8"
}
@PostConstruct (3)
fun initialize() {
initialized = true
}
}
1 | The PostConstruct annotation is imported |
2 | A field is defined that requires initialization |
3 | A method is annotated with @PostConstruct and will be invoked once the object is constructed and fully injected. |
To manage when a bean is constructed, see the section on bean scopes.