When The Context Starts
If you wish for a particular method to be invoked when a bean is constructed then you can use the javax.annotation.PostConstruct
annotation:
import javax.annotation.PostConstruct; (1)
import javax.inject.Singleton;
@Singleton
public class V8Engine implements Engine {
private int cylinders = 8;
private boolean initialized = false; (2)
public String start() {
if(!initialized) {
throw new IllegalStateException("Engine not initialized!");
}
return "Starting V8";
}
@Override
public int getCylinders() {
return cylinders;
}
public boolean isIntialized() {
return this.initialized;
}
@PostConstruct (3)
public void initialize() {
this.initialized = true;
}
}
import javax.annotation.PostConstruct (1)
import javax.inject.Singleton
@Singleton
class V8Engine implements Engine {
int cylinders = 8
boolean initialized = false (2)
String start() {
if(!initialized) throw new IllegalStateException("Engine not initialized!")
return "Starting V8"
}
@PostConstruct (3)
void initialize() {
this.initialized = true
}
}
import javax.annotation.PostConstruct
import javax.inject.Singleton
@Singleton
class V8Engine : Engine {
override val cylinders = 8
var isIntialized = false
private set (2)
override fun start(): String {
check(isIntialized) { "Engine not initialized!" }
return "Starting V8"
}
@PostConstruct (3)
fun initialize() {
this.isIntialized = 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. |