Bird
0
0

Given this Spring Boot bean code:

medium📝 Debug Q14 of 15
Spring Boot - Spring Annotations
Given this Spring Boot bean code:
public class ResourceBean {

    @PostConstruct
    public void setup() {
        System.out.println("Setup resources");
    }

    @PreDestroy
    public void cleanup() {
        System.out.println("Cleanup resources");
    }

    public void start() {
        System.out.println("Start method called");
    }

}

When running the application, the developer notices that "Cleanup resources" is never printed on shutdown. What is the most likely cause?
AThe @PostConstruct method prevents @PreDestroy from running
BThe @PreDestroy method must be static to run correctly
CThe cleanup() method must be called manually to run
DThe bean is not managed by Spring, so lifecycle annotations are ignored
Step-by-Step Solution
Solution:
  1. Step 1: Check if bean is managed by Spring

    @PostConstruct and @PreDestroy only work if Spring manages the bean lifecycle (e.g., via @Component or @Bean).
  2. Step 2: Understand why cleanup isn't called

    If the bean is created manually (new keyword), Spring won't call lifecycle methods, so cleanup() won't run automatically.
  3. Final Answer:

    The bean is not managed by Spring, so lifecycle annotations are ignored -> Option D
  4. Quick Check:

    Lifecycle annotations need Spring-managed beans [OK]
Quick Trick: Lifecycle methods run only on Spring-managed beans [OK]
Common Mistakes:
  • Thinking @PreDestroy must be static
  • Assuming @PostConstruct blocks @PreDestroy
  • Believing cleanup() runs without Spring management

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes