MODULE 4 · TOPIC 3 · VISUAL SPRING FRAMEWORK LAB

Inversion of Control and Dependency Injection

Inversion of Control shifts object assembly and lifecycle responsibility from application code to a container. Dependency injection is a technique for supplying collaborators through constructor arguments, setters, fields or factory methods. Instead of a service creating its own concrete repository, the container chooses a registered implementation and supplies it. This reduces coupling and makes tests easier, but does not eliminate the need to design interfaces, validate dependencies and avoid circular graphs.

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. Control inversion — who creates the object?

With direct construction, the caller owns the dependency choice. With DI, an external composition root or container supplies the object. Spring’s bean factory uses definitions and dependencies to determine construction order.

Why this example? Compare hardcoded construction against external configuration.

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

    With direct construction, the caller owns the dependency choice. With DI, an external composition root or container supplies the object. Spring’s bean factory uses definitions and dependencies to determine construction order.

    Try and observe

    Notice who chooses the implementation and who calls pay.

    2. Dependency graph and creation order

    Required constructor dependencies must be available before the dependent bean is constructed. A dependency graph is directed from a consumer toward its collaborators. Acyclic chains can be constructed bottom-up.

    Why this example? Trace Controller → Service → Repository and compare a missing leaf.

    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

      Required constructor dependencies must be available before the dependent bean is constructed. A dependency graph is directed from a consumer toward its collaborators. Acyclic chains can be constructed bottom-up.

      Try and observe

      Follow the resolution chain back to the controller.

      3. Interface-based implementation switching

      An interface allows multiple implementations. The container can supply one selected by configuration; business code need not depend on a concrete class. If multiple unqualified candidates exist, Spring may reject ambiguous single-bean injection.

      Why this example? Switch between email and SMS notification implementations.

      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

        An interface allows multiple implementations. The container can supply one selected by configuration; business code need not depend on a concrete class. If multiple unqualified candidates exist, Spring may reject ambiguous single-bean injection.

        Try and observe

        Inspect which object is injected and what gets printed.

        4. Constructor dependency cycle

        A constructor cycle occurs when A requires B during construction and B requires A before either object exists. Spring cannot create the two required instances in ordinary constructor wiring. Refactor the responsibilities rather than relying on circular-reference workarounds.

        Why this example? Compare a two-bean cycle with a one-directional dependency.

        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 constructor cycle occurs when A requires B during construction and B requires A before either object exists. Spring cannot create the two required instances in ordinary constructor wiring. Refactor the responsibilities rather than relying on circular-reference workarounds.

          Try and observe

          Follow the repeated request for A and the failure.

          5. Required versus optional dependencies

          Required dependencies make failure explicit during bean creation. Optional<T> or ObjectProvider<T> can express a genuine optional collaborator; using optional injection for a required service merely hides configuration errors.

          Why this example? Compare optional audit logging with required audit logging when no audit bean exists.

          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

            Required dependencies make failure explicit during bean creation. Optional<T> or ObjectProvider<T> can express a genuine optional collaborator; using optional injection for a required service merely hides configuration errors.

            Try and observe

            Check whether the core service can be constructed.

            6. Deferred dependency lookup with ObjectProvider

            A provider can defer bean resolution until a method needs it. It is useful when a singleton needs a fresh prototype or an optional object, but it introduces an explicit lookup boundary and should be used intentionally.

            Why this example? Compare direct prototype injection and a provider in a singleton.

            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 provider can defer bean resolution until a method needs it. It is useful when a singleton needs a fresh prototype or an optional object, but it introduces an explicit lookup boundary and should be used intentionally.

              Try and observe

              Request the collaborator twice and inspect the two IDs.

              API and configuration reference

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

              API / settingWhy and when to use it
              ApplicationContextOwns bean creation and wiring
              @BeanDeclare an object factory
              @ComponentMark a scan candidate
              @QualifierNarrow candidate selection
              ObjectProvider<T>Request a dependency lazily/on demand
              BeanCurrentlyInCreationExceptionCommon constructor cycle failure

              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. Manual DI without framework

              Procedure

              1. Create these types in a Java file.
              2. Run Main.main and compare the two gateway implementations.
              3. Notice that the service does not instantiate its own gateway.
              Code / configuration
              interface Gateway { void pay(int amount); }
              class PaymentService {
                private final Gateway gateway;
                PaymentService(Gateway gateway) { this.gateway = gateway; }
                void pay(int amount) { gateway.pay(amount); }
              }
              class Main {
                public static void main(String[] args) {
                  new PaymentService(a -> System.out.println("TEST " + a)).pay(100);
                  new PaymentService(a -> System.out.println("LIVE DEMO " + a)).pay(100);
                }
              }
              Expected result: Both calls use identical service code with different collaborators.

              2. Let Spring assemble the same objects

              Procedure

              1. Add spring-context and import org.springframework.context.annotation.*.
              2. Register Config in AnnotationConfigApplicationContext.
              3. Retrieve PaymentService and call pay(100), then replace the factory implementation.
              Code / configuration
              @Configuration
              class Config {
                @Bean Gateway gateway() { return a -> System.out.println("DEMO " + a); }
                @Bean PaymentService paymentService(Gateway g) { return new PaymentService(g); }
              }
              Expected result: Spring resolves the Gateway factory parameter and injects it into PaymentService.

              Predict the outcome before you run

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

              1. Predict the outcome: Assembly style = Container injection. Which path is taken and why?

              Application calls the assembled bean. Expected state: 100.

              2. Predict the outcome: Notification channel = SMS. Which path is taken and why?

              No real SMS is sent. Expected state: SMS.

              3. Predict the outcome: Audit design = Required audit. Which path is taken and why?

              Fail fast rather than silently skip auditing. Expected state: UnsatisfiedDependencyException.

              Hands-on practice and assessment

              Programming challenge

              Create a PaymentService that depends on a PaymentGateway interface. Inject a real-looking console gateway and a fake gateway, then verify the same service works with both.

              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

              Prefer constructor injection for required collaborators. DI can also be done manually; IoC is broader than dependency injection.