MODULE 4 · TOPIC 8 · VISUAL SPRING FRAMEWORK LAB

Bean Scopes and Life Cycle

A bean scope controls how instances are obtained and reused. Singleton is one managed instance per bean definition in a container; prototype creates a new instance for each lookup. Request, session, application and websocket scopes require appropriate web-aware infrastructure. The container runs lifecycle callbacks around initialization and destruction, but prototype destruction is the client’s responsibility. Scope choice changes identity and state sharing, not the class definition itself.

Browser-based Spring simulations. Change inputs and trace bean wiring, application layers, configuration and transaction behavior. No real Java, Spring or database operations are executed.

1. Singleton and prototype identity

A singleton is shared within a bean definition and context; prototype creation occurs on each lookup. Two variables may point to the same object or different objects, affecting mutable state.

Why this example? Look up a counter twice, increment via reference A and inspect B.

Why this step happens
See all steps in this scenario
    Java / Spring configuration
    Application / simulation outputConsole
    Data operationsCompact blocks
    CurrentResultError / rejected

    Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

    What this animation explains

    A singleton is shared within a bean definition and context; prototype creation occurs on each lookup. Two variables may point to the same object or different objects, affecting mutable state.

    Try and observe

    Compare B after the increment.

    2. Request and session scope across users

    In a servlet web application, request scope follows the current HTTP request and session scope follows the current HTTP session. Two requests in the same session share a session-scoped target but not a request-scoped target. Separate users have separate sessions.

    Why this example? Trace user A twice and user B once under different scopes.

    Why this step happens
    See all steps in this scenario
      Java / Spring configuration
      Application / simulation outputConsole
      Data operationsCompact blocks
      CurrentResultError / rejected

      Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

      What this animation explains

      In a servlet web application, request scope follows the current HTTP request and session scope follows the current HTTP session. Two requests in the same session share a session-scoped target but not a request-scoped target. Separate users have separate sessions.

      Try and observe

      Inspect IDs and the associated request or session.

      3. Bean lifecycle — initialize and destroy

      For a normal singleton, Spring instantiates the object, populates dependencies, invokes initialization callbacks, exposes the processed bean (possibly a proxy) and later invokes destruction callbacks when the context closes. Prototype initialization is supported, but destruction is not automatically managed.

      Why this example? Compare callback traces for a singleton and a requested prototype.

      Why this step happens
      See all steps in this scenario
        Java / Spring configuration
        Application / simulation outputConsole
        Data operationsCompact blocks
        CurrentResultError / rejected

        Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

        What this animation explains

        For a normal singleton, Spring instantiates the object, populates dependencies, invokes initialization callbacks, exposes the processed bean (possibly a proxy) and later invokes destruction callbacks when the context closes. Prototype initialization is supported, but destruction is not automatically managed.

        Try and observe

        Close the context and compare cleanup behavior.

        4. Lazy versus eager startup

        Eager singleton pre-instantiation discovers many configuration errors during context refresh. Lazy singleton creation shifts work to first access unless needed by another eager bean. Lazy does not mean prototype.

        Why this example? Change initialization mode and observe when work is done.

        Why this step happens
        See all steps in this scenario
          Java / Spring configuration
          Application / simulation outputConsole
          Data operationsCompact blocks
          CurrentResultError / rejected

          Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

          What this animation explains

          Eager singleton pre-instantiation discovers many configuration errors during context refresh. Lazy singleton creation shifts work to first access unless needed by another eager bean. Lazy does not mean prototype.

          Try and observe

          Compare refresh and first lookup.

          5. Prototype injection into singleton

          Injecting a prototype directly into a singleton happens once, at construction. A provider resolves a prototype on every getObject call. A scoped proxy is another option, with different method-call semantics.

          Why this example? Compare a stored Job reference and a provider lookup.

          Why this step happens
          See all steps in this scenario
            Java / Spring configuration
            Application / simulation outputConsole
            Data operationsCompact blocks
            CurrentResultError / rejected

            Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

            What this animation explains

            Injecting a prototype directly into a singleton happens once, at construction. A provider resolves a prototype on every getObject call. A scoped proxy is another option, with different method-call semantics.

            Try and observe

            Observe the job IDs across two tasks.

            6. Scope boundary and scoped proxy

            A singleton may need a request-scoped dependency. A scoped proxy can be injected at startup and resolve the real target during an active request. Calling it without the required active request scope can still fail.

            Why this example? Compare invoking the same proxy during a request and outside one.

            Why this step happens
            See all steps in this scenario
              Java / Spring configuration
              Application / simulation outputConsole
              Data operationsCompact blocks
              CurrentResultError / rejected

              Change inputs and step through the example. Code and output are illustrative; actual Spring logs and initialization order may differ. Use the worked examples in a real project.

              What this animation explains

              A singleton may need a request-scoped dependency. A scoped proxy can be injected at startup and resolve the real target during an active request. Calling it without the required active request scope can still fail.

              Try and observe

              Notice the proxy identity remains fixed while target availability changes.

              API and configuration reference

              Refer to these APIs and settings while building a real Spring project.

              API / settingWhy and when to use it
              @Scope("prototype")Create a new bean per lookup
              @LazyDefer eligible singleton initialization
              @RequestScopeOne scoped target per HTTP request
              @SessionScopeOne scoped target per HTTP session
              @PostConstructInitialization callback (Jakarta annotation)
              @PreDestroyDestruction callback for managed lifecycle

              Worked practical examples

              Follow these procedures with the Java 21 / Spring Framework 6.2.0 teaching project. Unless complete files are provided, the code is a focused snippet requiring the indicated imports, companion classes and configuration.

              1. Compare singleton and prototype

              Procedure

              1. Add spring-context and import org.springframework.context.annotation.*.
              2. Create Config with two separate bean definitions.
              3. Retrieve each by name twice and compare reference identity.
              Code / configuration
              @Configuration class Config {
               @Bean Job shared() { return new Job(); }
               @Bean @Scope("prototype") Job fresh() { return new Job(); }
              }
              class Job {}
              // In main, with ctx open:
              System.out.println(ctx.getBean("shared") == ctx.getBean("shared"));
              System.out.println(ctx.getBean("fresh") == ctx.getBean("fresh"));
              Expected result: Prints true and false respectively.

              2. Lifecycle callbacks

              Procedure

              1. Add jakarta.annotation:jakarta.annotation-api:2.1.1 to the Maven project.
              2. Register ResourceBean as a singleton through @Bean.
              3. Retrieve it, then close the context.
              Code / configuration
              class ResourceBean {
               @jakarta.annotation.PostConstruct
               void init() { System.out.println("open resource"); }
               @jakarta.annotation.PreDestroy
               void cleanup() { System.out.println("close resource"); }
              }
              Expected result: Initialization is called before normal use and destruction on normal singleton shutdown.

              Predict the outcome before you run

              Try answering these questions, then expand each answer and repeat the appropriate simulation.

              1. Predict the outcome: Scope = Prototype. Which path is taken and why?

              B refers to a different object. Expected state: 0.

              2. Predict the outcome: Lifecycle scope = Prototype. Which path is taken and why?

              Client must manage prototype cleanup. Expected state: No automatic destroy.

              3. Predict the outcome: Injection design = Provider. Which path is taken and why?

              Second lookup creates another prototype. Expected state: Job #2.

              Hands-on practice and assessment

              Programming challenge

              Create singleton and prototype Job beans, request each twice, compare references, then close the context and record callbacks.

              Edit this practice scratchpad and copy it into your real Java project. The browser does not compile arbitrary Java.

              Quick assessment

              Key points and real Spring notes

              Use stateless singleton services where possible. Request/session scoped beans require active scopes, and a scoped proxy/provider can bridge shorter lifetimes.