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. @Override
  8. public String start() {
  9. if(!initialized) {
  10. throw new IllegalStateException("Engine not initialized!");
  11. }
  12. return "Starting V8";
  13. }
  14. @Override
  15. public int getCylinders() {
  16. return cylinders;
  17. }
  18. public boolean isIntialized() {
  19. return this.initialized;
  20. }
  21. @PostConstruct (3)
  22. public void initialize() {
  23. this.initialized = true;
  24. }
  25. }
  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. @Override
  8. String start() {
  9. if(!initialized) throw new IllegalStateException("Engine not initialized!")
  10. return "Starting V8"
  11. }
  12. @PostConstruct (3)
  13. void initialize() {
  14. this.initialized = true
  15. }
  16. }
  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.