Bean lifecycle and scopes
What you will learn
A bean scope answers how many instances a container supplies and when. Lifecycle callbacks handle setup and cleanup. Keep singleton services stateless or thread-safe, and place short-lived mutable state in a method or a deliberately shorter-lived object.
- Distinguish singleton and prototype identity.
- Explain setup, destruction and ownership.
- Configure profiles and explicit property precedence before refresh.
Plain Java examples use javac --release 21 Main.java then java Main in a fresh folder. Framework examples require the separate pinned Maven lab; their outputs are predictions from source review, not execution evidence. Do not copy all files into one Main.java.
Create fresh task state
public class Main { static final class Draft { private int count; void add() { count++; } int count() { return count; } } static final java.util.function.Supplier<Draft> FACTORY = Draft::new; public static void main(String[] args) { Draft first = FACTORY.get(); Draft second = FACTORY.get(); first.add(); System.out.println(first == second); System.out.println(first.count() + ":" + second.count()); }}Expected output:
false1:0A plain factory demonstrates fresh state. This is not a Spring scope test.
Identity and ownership
Spring singleton scope means one shared instance per bean definition per container, not one instance per JVM or class. A prototype request creates a fresh managed instance, but Spring does not invoke its configured destruction callbacks. If a singleton receives a prototype through its constructor, that reference stays the same; use ObjectProvider<T>.getObject() for an on-demand instance. Request, session, application and websocket scopes need the corresponding web infrastructure; this non-web lab does not activate them.
Lifecycle
For ordinary singleton beans, creation, dependency population, initialization callbacks and post-processing precede ordinary use. On context closure Spring destroys managed singleton beans. Use @Bean(initMethod="start", destroyMethod="stop") or Jakarta @PostConstruct and @PreDestroy with the appropriate annotation dependency. A BeanPostProcessor can wrap a bean with a proxy. Do not rely on every possible callback order without testing your exact configuration. Avoid I/O in constructors and avoid exposing a partially initialized object. The context owns the singleton; callers own prototype resources.
Profiles and property sources
Profiles control which definitions are registered: @Profile("lab") is active only when that profile matches. Set active profiles before refresh. Environment resolves properties from ordered property sources; addFirst gives a synthetic MapPropertySource priority over existing sources. Read a required property via getRequiredProperty and validate at startup. Core Spring does not automatically implement Spring Boot application.yml conventions. Never log secrets or use per-request mutable fields in a shared singleton. @Scope("prototype") alone does not make concurrent sharing safe.
Close a resource at its owner boundary
public class Main { static final class Resource implements AutoCloseable { private boolean open = true; void use() { if (!open) throw new IllegalStateException("closed"); } public void close() { open = false; } } public static void main(String[] args) { Resource resource = new Resource(); try (resource) { resource.use(); System.out.println("used"); } try { resource.use(); } catch (IllegalStateException ex) { System.out.println(ex.getMessage()); } }}Expected output:
usedclosedJava ownership is explicit here; Spring callbacks are a separate contract.
Inspect scope, profiles and shutdown
Source-reviewed, NOT RUN. File lab-fixtures/spring-v37/src/main/java/lab/spring/ScopeDemo.java; use the companion Maven lab instructions.
package lab.spring;import java.util.Map;import org.springframework.beans.factory.ObjectProvider;import org.springframework.context.annotation.*;import org.springframework.core.env.Environment;import org.springframework.core.env.MapPropertySource;public class ScopeDemo { record Label(String text) {} static class Draft {} record Factory(ObjectProvider<Draft> drafts) { Draft next() { return drafts.getObject(); } } static class Resource { public void start() { System.out.println("start"); } public void stop() { System.out.println("stop"); } } @Configuration(proxyBeanMethods = false) static class Config { @Bean @Profile("lab") Label label(Environment env) { return new Label(env.getRequiredProperty("lab.label")); } @Bean @Scope("prototype") Draft draft() { return new Draft(); } @Bean Factory factory(ObjectProvider<Draft> drafts) { return new Factory(drafts); } @Bean(initMethod="start", destroyMethod="stop") @Lazy Resource resource() { return new Resource(); } } public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext()) { context.getEnvironment().setActiveProfiles("lab"); context.getEnvironment().getPropertySources().addFirst( new MapPropertySource("lab-only", Map.of("lab.label", "warehouse"))); context.register(Config.class); context.refresh(); var label = context.getBean(Label.class); var factory = context.getBean(Factory.class); System.out.println("same=" + (label == context.getBean(Label.class))); System.out.println("fresh=" + (factory.next() != factory.next())); System.out.println("label=" + label.text()); context.getBean(Resource.class); } }}Predicted stdout:
same=truefresh=truelabel=warehousestartstopThe demo prints identity checks and property resolution. The lifecycle bean is lazy and created explicitly after those checks.
Common mistakes
A singleton with a mutable request field can leak one user’s data into another request. A prototype injected once into a singleton does not refresh itself. Do not assume closing a context destroys prototypes; arrange cleanup for each caller-owned instance. Do not apply a web request scope to a plain context.
Practice
Implement a request-local counter factory. Create two counters, increment one twice and the other once. Show distinct identity and independent values. Explain how ObjectProvider would preserve fresh creation in a Spring singleton.
Expected output:
true2:1Compare with the manual review criteria.
Official reading: Bean · Scopes · Environment · Lifecycle. Framework execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bean lifecycle and scopes — knowledge check
Spring fundamentals and boundary reasoning.
What does singleton scope mean in Spring?
What happens to a prototype injected into a singleton constructor?
Who arranges destruction of a prototype resource?
When should the active profiles for this lab be set?
What does adding a property source first do?