MODULE 4 · TOPIC 6 · VISUAL SPRING FRAMEWORK LAB

Constructor Injection

Constructor injection makes collaborators explicit parameters of object construction. Required fields can be final and validated immediately, so the object is ready for use after construction. Spring can select a single constructor without @Autowired; multiple constructors need unambiguous selection rules. Constructor injection also works in ordinary unit tests, outside a container. This topic compares resolution, optionality, cycles and immutability using practical object 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. Constructor argument resolution

The container resolves constructor arguments before constructing a dependent bean. A single constructor can be selected implicitly. A missing required candidate prevents bean creation.

Why this example? Compare registered and missing repositories.

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

    The container resolves constructor arguments before constructing a dependent bean. A single constructor can be selected implicitly. A missing required candidate prevents bean creation.

    Try and observe

    Observe the order of repository construction and service construction.

    2. Multiple constructors and explicit selection

    If a component has multiple constructors, Spring applies constructor resolution rules. An explicitly required @Autowired constructor selects that entry point. With no annotated constructor and an available default constructor, Spring can use the default.

    Why this example? Compare explicit required constructor and an unannotated no-arg fallback.

    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

      If a component has multiple constructors, Spring applies constructor resolution rules. An explicitly required @Autowired constructor selects that entry point. With no annotated constructor and an available default constructor, Spring can use the default.

      Try and observe

      Notice which constructor is invoked.

      3. Immutable dependency references

      A final field can be assigned during construction and cannot later be reassigned. This is useful for stable wiring, but does not freeze the collaborator’s internal state.

      Why this example? Compare a stable repository reference and an attempted reassignment.

      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 final field can be assigned during construction and cannot later be reassigned. This is useful for stable wiring, but does not freeze the collaborator’s internal state.

        Try and observe

        Observe why javac rejects the second assignment.

        4. Resolve multiple constructor parameters

        A dependent bean may need multiple independent collaborators, such as Repo and Clock. All required parameters must resolve. The construction order between unrelated dependencies is not an API contract; the demo shows one valid order.

        Why this example? Remove one collaborator and observe that partial dependencies do not make the service ready.

        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 dependent bean may need multiple independent collaborators, such as Repo and Clock. All required parameters must resolve. The construction order between unrelated dependencies is not an API contract; the demo shows one valid order.

          Try and observe

          Check which parameter prevents construction.

          5. Manual dependency injection for unit tests

          Constructor parameters allow a test to supply a fake without starting Spring or connecting to a database. This tests service behavior in isolation, not the real container or persistence integration.

          Why this example? Swap a repository response and observe the service return value.

          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

            Constructor parameters allow a test to supply a fake without starting Spring or connecting to a database. This tests service behavior in isolation, not the real container or persistence integration.

            Try and observe

            Change the fake response; the service source is unchanged.

            6. Break a mandatory dependency cycle

            A required constructor cycle makes ordinary assembly impossible. Refactoring a shared operation into a third collaborator can remove the cycle and create an acyclic graph. The shared collaborator must not itself depend back on either consumer.

            Why this example? Compare mutual service dependencies with a shared coordinator.

            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 required constructor cycle makes ordinary assembly impossible. Refactoring a shared operation into a third collaborator can remove the cycle and create an acyclic graph. The shared collaborator must not itself depend back on either consumer.

              Try and observe

              Follow the graph and observe startup status.

              API and configuration reference

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

              API / settingWhy and when to use it
              public Service(Repo repo)Declare the required collaborator
              Objects.requireNonNullValidate constructor arguments
              @AutowiredSelect an eligible injection constructor
              @QualifierNarrow candidate choice at the parameter
              @Bean service(Repo r)Factory parameter injection
              new Service(fakeRepo)Test without a Spring container

              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. Build a required dependency

              Procedure

              1. Create the interface and service.
              2. Create an in-memory Repo implementation and invoke the service in main.
              3. Register the same service with @Bean or @Service later.
              Code / configuration
              interface Repo { String find(); }
              class Service {
               private final Repo repo;
               Service(Repo repo) { this.repo = java.util.Objects.requireNonNull(repo); }
               String read() { return repo.find(); }
              }
              // In main: System.out.println(new Service(() -> "Anu").read());
              Expected result: Anu is returned with no Spring container needed.

              2. Constructor selection in Spring

              Procedure

              1. Add spring-context.
              2. Place Service and RepoImpl in the scanned package.
              3. Use @ComponentScan and obtain Service from the context.
              Code / configuration
              @Service
              class StudentService {
               private final Repo repo;
               StudentService(Repo repo) { this.repo = repo; }
               public String read() { return repo.find(); }
              }
              @Repository
              class RepoImpl implements Repo {
               public String find() { return "Anu"; }
              }
              Expected result: The single constructor receives RepoImpl; no @Autowired annotation is required.

              Predict the outcome before you run

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

              1. Predict the outcome: Repo bean = Missing. Which path is taken and why?

              The service constructor cannot be called. Expected state: UnsatisfiedDependencyException.

              2. Predict the outcome: Action = Reassign final reference. Which path is taken and why?

              The compiler rejects assignment to the final field. Expected state: Invalid.

              3. Predict the outcome: Fake response = Student absent. Which path is taken and why?

              The fallback handles an empty result. Expected state: Not found.

              Hands-on practice and assessment

              Programming challenge

              Build a service with a final repository and clock. Instantiate it manually in a test, then register the same service in Spring.

              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

              A final reference does not make the referenced object immutable or thread-safe. Constructor injection does not solve cyclic mandatory dependencies.