Bird
0
0

Given the following Spring Boot bean code:

medium📝 component behavior Q4 of 15
Spring Boot - Spring Annotations
Given the following Spring Boot bean code:
public class MyService {

    @PostConstruct
    public void start() {
        System.out.println("Starting service");
    }

    @PreDestroy
    public void stop() {
        System.out.println("Stopping service");
    }
}

What will be printed when the application context starts and then closes?
ANo output printed
B"Stopping service" printed at start, "Starting service" printed at shutdown
COnly "Starting service" printed at start
D"Starting service" printed at start, "Stopping service" printed at shutdown
Step-by-Step Solution
Solution:
  1. Step 1: Understand @PostConstruct behavior

    The start() method runs once after bean initialization, printing "Starting service".
  2. Step 2: Understand @PreDestroy behavior

    The stop() method runs once before bean destruction, printing "Stopping service".
  3. Final Answer:

    "Starting service" printed at start, "Stopping service" printed at shutdown -> Option D
  4. Quick Check:

    @PostConstruct prints start, @PreDestroy prints stop [OK]
Quick Trick: @PostConstruct runs at start, @PreDestroy runs at shutdown [OK]
Common Mistakes:
  • Swapping the order of printed messages
  • Assuming only one method runs
  • Thinking methods run multiple times

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes