Databases, Spring and microservices · 2. Spring Core and Spring MVC, lesson 3 of 8

Bean scopes and lifecycle

Intermediate3 min read@since 17Code runs on your Java 25
Explain it forThe essentials plus production detail and pitfalls.

Scopes:

  • singleton (the default): one instance per container. It must be stateless or thread-safe.
  • prototype: a new instance every time one is requested.
  • Web scopes: request, session and application.

The lifecycle of a bean:

  1. Instantiate it (call the constructor).
  2. Inject its dependencies.
  3. Run BeanPostProcessor hooks, where annotations like @Autowired are processed.
  4. Call init callbacks: @PostConstruct, afterPropertiesSet() or @Bean(initMethod = ...).
  5. Wrap it in a proxy if needed (for @Transactional, @Async and other aspects).
  6. Use it.
  7. On shutdown, call @PreDestroy (not called for prototype beans).
Diagram
Spring container lab

A prototype inside a singleton

A singleton is created once, so a prototype injected into it is also created only once: every caller shares it. When you need a fresh instance each time, inject ObjectProvider<T> and call getObject(), or use a method annotated with @Lookup. The scopes lab above shows this happening.

Java
@Service
class CheckoutService {
    private final ObjectProvider<ShoppingCart> carts;            // not the cart itself
    CheckoutService(ObjectProvider<ShoppingCart> carts) { this.carts = carts; }

    Receipt checkout(List<Item> items) {
        ShoppingCart cart = carts.getObject();                     // a new prototype every call
        items.forEach(cart::add);
        return cart.pay();
    }
}

Lifecycle callbacks

Run code after a bean is fully set up with @PostConstruct (validate configuration, warm a cache) and before shutdown with @PreDestroy (close clients, stop threads). Alternatives: InitializingBean/DisposableBean interfaces, or @Bean(initMethod = "...", destroyMethod = "...") for classes you don't own. Prototype beans are never destroyed by the container: you clean them up yourself.

BeanPostProcessor and BeanFactoryPostProcessor

These are how Spring extends itself. A BeanFactoryPostProcessor changes bean *definitions* before any bean exists (resolving ${...} placeholders, for example). A BeanPostProcessor works on each bean *instance* before and after initialisation: it processes @Autowired and @Value, and it is where proxies for @Transactional, @Async and @Cacheable are created.

Example

Java
@Component
public class CourseCache {
    private final Map<Long, Course> cache = new ConcurrentHashMap<>();   // thread-safe
    private final CourseRepository repo;

    public CourseCache(CourseRepository repo) { this.repo = repo; }

    @PostConstruct
    void warmUp() {                                   // runs after injection
        repo.findTop20ByOrderByRatingDesc().forEach(c -> cache.put(c.getId(), c));
    }

    @PreDestroy
    void shutdown() { cache.clear(); }
}

@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
class ReportBuilder {
    private final List<String> lines = new ArrayList<>();
}

Common mistake

Storing per-user data in a field of a singleton @Service. Every request shares it, so users see each other's data.

Under the hood

Injecting a prototype bean into a singleton gives you one prototype instance forever, because injection happens only once. Inject an ObjectProvider<ReportBuilder> and call getObject() each time, or use a @Lookup method. @PostConstruct and @PreDestroy come from jakarta.annotation in Spring 6+.

Check yourself

What is the default Spring bean scope?

How this connects

Part of Job-ready backend developer, Spring Core and Spring Security in depth.

Was this lesson helpful?

Finished reading? Mark it complete to track your progress.