MODULE 4 · TOPIC 7 · VISUAL SPRING FRAMEWORK LAB

Autowiring

Autowiring is Spring’s mechanism for resolving injection points from registered bean definitions. Candidate selection primarily uses type, then qualifying metadata, primary/fallback status and other resolution rules such as matching names. A single required injection point must resolve unambiguously. Collections may receive multiple beans; optional injection and providers express a different contract. Component scanning registers beans, while autowiring connects them.

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. Type-based candidate resolution

A single-valued required injection point needs one resolvable candidate. No match causes a missing dependency; multiple equally eligible candidates without a qualifier, primary or other tie-breaker cause ambiguity.

Why this example? Change the number of registered Notifier beans.

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 single-valued required injection point needs one resolvable candidate. No match causes a missing dependency; multiple equally eligible candidates without a qualifier, primary or other tie-breaker cause ambiguity.

    Try and observe

    Watch the candidate count and the outcome.

    2. Primary preference versus explicit qualifier

    @Primary gives preference when multiple eligible beans satisfy a single-valued injection. A qualifier narrows the set first; it can select a nonprimary implementation. Primary does not hide other registered beans.

    Why this example? Choose unqualified or qualified injection of email and sms.

    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

      @Primary gives preference when multiple eligible beans satisfy a single-valued injection. A qualifier narrows the set first; it can select a nonprimary implementation. Primary does not hide other registered beans.

      Try and observe

      Inspect the candidate chosen and output channel.

      3. Collections and ordered dispatch

      List<T> injection gathers eligible matching beans and can honor @Order/Ordered ordering. It differs from scalar injection: @Primary does not exclude the other beans. @Order is not a general singleton startup-order guarantee.

      Why this example? Compare a scalar Notifier with a list of Notifiers.

      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

        List<T> injection gathers eligible matching beans and can honor @Order/Ordered ordering. It differs from scalar injection: @Primary does not exclude the other beans. @Order is not a general singleton startup-order guarantee.

        Try and observe

        Observe invocation count and output order.

        4. Field versus method injection

        Autowired fields are populated by container post-processing after object construction. Methods are also injection points. Objects constructed manually with new are not automatically post-processed by Spring.

        Why this example? Compare a container-managed component and a manually constructed instance.

        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

          Autowired fields are populated by container post-processing after object construction. Methods are also injection points. Objects constructed manually with new are not automatically post-processed by Spring.

          Try and observe

          Check why the field remains null outside the container.

          5. Optional and deferred lookup

          Optional<T> supports absence for one expected dependency. ObjectProvider<T> can resolve on demand; getIfAvailable returns null for absence, but neither removes ambiguity when multiple unresolved candidates exist.

          Why this example? Compare the provider with and without a registered audit bean.

          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

            Optional<T> supports absence for one expected dependency. ObjectProvider<T> can resolve on demand; getIfAvailable returns null for absence, but neither removes ambiguity when multiple unresolved candidates exist.

            Try and observe

            Watch lookup at method execution instead of startup.

            6. Autowire debugging — qualifiers and names

            Qualifiers narrow eligible type candidates. A typo can eliminate all matches even though beans of that type exist. Error messages and registry inspection help separate registration problems from selection problems.

            Why this example? Compare matching and misspelled qualifiers.

            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

              Qualifiers narrow eligible type candidates. A typo can eliminate all matches even though beans of that type exist. Error messages and registry inspection help separate registration problems from selection problems.

              Try and observe

              Inspect registered beans and the exact qualifier value.

              API and configuration reference

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

              API / settingWhy and when to use it
              @AutowiredResolve a dependency from the container
              @Qualifier("email")Narrow type-matching candidates
              @PrimaryPrefer one candidate for a single-valued injection point
              @OrderOrder eligible collection elements
              Optional<T>Represent an optional collaborator
              ObjectProvider<T>Perform deferred lookup

              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. Resolve two implementations

              Procedure

              1. Create the Notifier interface.
              2. Register email and sms beans in Config.
              3. Inject a qualified Notifier into AlertService.
              Code / configuration
              @Configuration
              class Config {
               @Bean @Primary Notifier email() { return m -> System.out.println("EMAIL " + m); }
               @Bean Notifier sms() { return m -> System.out.println("SMS " + m); }
               @Bean AlertService alerts(@Qualifier("sms") Notifier n) { return new AlertService(n); }
              }
              Expected result: The qualifier selects sms despite email being primary.

              2. Inject an ordered collection

              Procedure

              1. Declare two Notifier components with @Order values.
              2. Register the service via scanning.
              3. Print the list in order.
              Code / configuration
              @Service
              class BroadcastService {
               private final List<Notifier> all;
               BroadcastService(List<Notifier> all) { this.all = all; }
               void send(String m) { all.forEach(n -> n.send(m)); }
              }
              Expected result: All eligible implementations receive the call. Provide the interface and imports.

              Predict the outcome before you run

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

              1. Predict the outcome: Candidates = Two candidates. Which path is taken and why?

              Spring cannot choose a unique object. Expected state: NoUniqueBeanDefinitionException.

              2. Predict the outcome: Injection type = List of Notifiers. Which path is taken and why?

              Invoke Email second. Expected state: 2 of 2.

              3. Predict the outcome: Audit registration = Audit absent. Which path is taken and why?

              The guard avoids dereferencing null. Expected state: null.

              Hands-on practice and assessment

              Programming challenge

              Register two Notifier implementations. Resolve one using @Primary or @Qualifier, then inject List<Notifier> to observe 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

              Do not use bean names accidentally to resolve ambiguity. Use explicit qualifier metadata when implementations have distinct roles. Examples use ordinary single-bean type resolution.