Bean Scopes & Lifecycle: Birth to Death

Bean Scopes & Lifecycle: Birth to Death in Java: A bean is any object Spring creates and manages for you.

Concept Explanation

A bean is any object Spring creates and manages for you. Understanding how many exist and when they are created explains most confusing Spring behaviour.


Scopes

ScopeInstancesUse for
singletonone per container (default)services, repositories
prototypea new one per injectionstateful helpers
requestone per HTTP requestrequest-scoped data
sessionone per user sessionper-user state
@Service                       // singleton by default
public class PricingService { }

@Service
@Scope("prototype")            // new instance every time it is asked for
public class ReportBuilder { }

The critical consequence: because services are singletons shared across all request threads, a mutable field on a service is a concurrency bug.

@Service
public class BadCounter {
    private int count = 0;              // shared by every thread!
    public void hit() { count++; }      // race condition
}

Keep beans stateless, or guard state with an AtomicInteger or a lock.


Lifecycle Hooks

@Service
public class CacheWarmer {

    private final ProductRepository repo;

    public CacheWarmer(ProductRepository repo) {   // 1. constructor injection
        this.repo = repo;
    }

    @PostConstruct
    public void warm() {                           // 2. after injection completes
        System.out.println("Preloading cache...");
    }

    @PreDestroy
    public void flush() {                          // 3. before shutdown
        System.out.println("Flushing cache...");
    }
}

Order: constructor → dependency injection → @PostConstruct → bean in use → @PreDestroy.

Note that @PreDestroy does not run for prototype beans — Spring hands them over and forgets them.


Common Mistakes

  1. Mutable singleton state: The most frequent production bug in Spring apps.
  2. Work in the constructor: Database calls belong in @PostConstruct; at constructor time dependencies may not be ready.
  3. Injecting a prototype into a singleton: You get exactly one prototype instance, captured forever. Inject an ObjectProvider instead.
  4. Field injection: @Autowired on a field hides dependencies and blocks final. Prefer constructor injection.

Best Practices

  • Constructor injection always: Dependencies become explicit, final, and trivially testable without Spring.
  • Default to stateless singletons: Reach for another scope only with a concrete reason.
  • Keep @PostConstruct fast: It runs during startup and delays readiness.

Practice Exercises

  1. The Instance Count: Create a singleton and a prototype bean that print in their constructors. Inject each three times and count the printouts.
  2. The Race: Build the BadCounter above, hit it from 100 threads, and observe the count falling short of 100. Fix it with AtomicInteger.
  3. The Lifecycle Trace: Add @PostConstruct and @PreDestroy logging to a bean and record the exact order relative to the constructor.