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:

  1. import javax.annotation.PostConstruct; (1)
  2. import javax.inject.Singleton;
  3. @Singleton
  4. public class V8Engine implements Engine {
  5. private int cylinders = 8;
  6. private boolean initialized = false; (2)
  7. public String start() {
  8. if(!initialized) {
  9. throw new IllegalStateException("Engine not initialized!");
  10. }
  11. return "Starting V8";
  12. }
  13. @Override
  14. public int getCylinders() {
  15. return cylinders;
  16. }
  17. public boolean isIntialized() {
  18. return this.initialized;
  19. }
  20. @PostConstruct (3)
  21. public void initialize() {
  22. this.initialized = true;
  23. }
  24. }
  1. import javax.annotation.PostConstruct (1)
  2. import javax.inject.Singleton
  3. @Singleton
  4. class V8Engine implements Engine {
  5. int cylinders = 8
  6. boolean initialized = false (2)
  7. String start() {
  8. if(!initialized) throw new IllegalStateException("Engine not initialized!")
  9. return "Starting V8"
  10. }
  11. @PostConstruct (3)
  12. void initialize() {
  13. this.initialized = true
  14. }
  15. }
  1. import javax.annotation.PostConstruct
  2. import javax.inject.Singleton
  3. @Singleton
  4. class V8Engine : Engine {
  5. override val cylinders = 8
  6. var isIntialized = false
  7. private set (2)
  8. override fun start(): String {
  9. check(isIntialized) { "Engine not initialized!" }
  10. return "Starting V8"
  11. }
  12. @PostConstruct (3)
  13. fun initialize() {
  14. this.isIntialized = true
  15. }
  16. }
1The PostConstruct annotation is imported
2A field is defined that requires initialization
3A method is annotated with @PostConstruct and will be invoked once the object is constructed and fully injected.