Bird
Raised Fist0
Spring Bootframework~10 mins

@Autowired for dependency injection in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - @Autowired for dependency injection
Start Application
↓
Spring scans for @Autowired
↓
Find dependency to inject
↓
Create or find bean instance
↓
Inject bean into target class
↓
Use injected bean in code
↓
Application runs with dependencies ready
Spring scans for @Autowired annotations, finds the needed beans, creates or retrieves them, and injects them into the target class before running the application.
Execution Sample
Spring Boot
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class Service {
  @Autowired
  private Repository repo;

  public void doWork() {
    repo.save();
  }
}
This code shows Spring injecting a Repository bean into Service using @Autowired, so Service can call repo.save() without manual setup.
Execution Table
StepActionEvaluationResult
1Spring starts and scans classesFind @Autowired on 'repo' fieldMarks 'repo' for injection
2Spring looks for Repository beanRepository bean found or createdRepository instance ready
3Spring injects Repository instance into Service.repoField 'repo' set with Repository instanceService.repo now references Repository bean
4Service.doWork() calledCalls repo.save()Repository.save() executes
5Application runs with dependencies injectedNo manual new Repository() neededDependency injection successful
💡 All dependencies injected, application runs with ready-to-use beans
Variable Tracker
VariableStartAfter InjectionAfter doWork() call
reponullRepository instanceRepository instance (used)
Key Moments - 3 Insights
Why is 'repo' null before injection but not after?
Before injection, Spring has not assigned the Repository instance, so 'repo' is null. After step 3 in execution_table, Spring injects the Repository bean, so 'repo' references the instance.
What happens if Spring cannot find a Repository bean to inject?
Spring will throw an error during startup because it cannot fulfill the @Autowired dependency, stopping the application from running.
Does @Autowired create a new instance every time?
No, by default Spring injects a singleton bean instance, so the same Repository object is reused unless configured otherwise.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'repo' after step 2?
Anull
BRepository instance
CNew Service instance
DUndefined
💡 Hint
Check variable_tracker column 'After Injection' and execution_table step 2 where bean is found but not yet injected
At which step does Spring inject the Repository bean into Service?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table step 3 where injection is described
If the Repository bean is missing, what will happen according to the key moments?
ASpring creates a new Repository automatically
BSpring throws an error and stops startup
CService runs with repo as null
DApplication runs but repo.save() does nothing
💡 Hint
Refer to key_moments about missing bean behavior
Concept Snapshot
@Autowired injects dependencies automatically.
Spring scans for @Autowired fields.
Finds or creates matching beans.
Injects bean instance into target.
No manual new needed.
Injection happens before use.
Full Transcript
When a Spring Boot application starts, it scans classes for the @Autowired annotation. When it finds a field marked with @Autowired, like 'repo' in the Service class, it looks for a matching bean to inject. If a Repository bean exists, Spring creates or retrieves it and injects it into the Service's 'repo' field. Before injection, 'repo' is null. After injection, 'repo' references the Repository instance. When Service calls doWork(), it uses the injected Repository to perform actions like save(). If Spring cannot find a required bean, it throws an error and stops the application from starting. This automatic wiring saves you from manually creating and passing dependencies.

Practice

(1/5)
1. What is the main purpose of the @Autowired annotation in Spring Boot?
easy
A. To create a new thread
B. To define a REST endpoint
C. To configure database connections
D. To automatically inject dependencies into a class

Solution

  1. Step 1: Understand the role of @Autowired and identify the correct purpose

    @Autowired is used to automatically provide the needed objects (dependencies) to a class without manual creation. It helps Spring Boot inject required components, making code cleaner and easier to maintain.
  2. Final Answer:

    To automatically inject dependencies into a class -> Option D
  3. Quick Check:

    @Autowired = automatic dependency injection [OK]
Hint: Remember: @Autowired links needed parts automatically [OK]
Common Mistakes:
  • Confusing @Autowired with REST endpoint annotations
  • Thinking @Autowired manages database setup
  • Assuming @Autowired creates new threads
2. Which of the following is the correct way to use @Autowired for field injection in a Spring Boot class?
easy
A. private Service service @Autowired;
B. @Autowired private Service service;
C. Service @Autowired service;
D. private @Autowired Service service;

Solution

  1. Step 1: Recall field injection syntax and match correct syntax

    The @Autowired annotation is placed before the field declaration with its access modifier. @Autowired private Service service; correctly places @Autowired before the field type and name.
  2. Final Answer:

    @Autowired private Service service; -> Option B
  3. Quick Check:

    @Autowired before field = correct syntax [OK]
Hint: Put @Autowired right before the field declaration [OK]
Common Mistakes:
  • Placing @Autowired after the field name
  • Putting @Autowired between type and variable name
  • Missing access modifier with @Autowired
3. Given the code below, what will be the output when myController.printServiceName() is called?

@Service
public class MyService {
    public String getName() { return "ServiceA"; }
}

@RestController
public class MyController {
    @Autowired
    private MyService myService;

    public void printServiceName() {
        System.out.println(myService.getName());
    }
}
medium
A. ServiceA
B. null
C. Compilation error
D. Runtime NullPointerException

Solution

  1. Step 1: Understand @Autowired effect and trace method call output

    Spring Boot injects an instance of MyService into MyController automatically. Calling getName() on injected myService returns "ServiceA" which is printed.
  2. Final Answer:

    ServiceA -> Option A
  3. Quick Check:

    Injected service returns "ServiceA" [OK]
Hint: Autowired injects instance, so method returns actual value [OK]
Common Mistakes:
  • Assuming myService is null without injection
  • Thinking code causes compilation error
  • Expecting NullPointerException due to missing initialization
4. What is wrong with the following Spring Boot code snippet?

@Service
public class UserService {
    private Repository repo;

    @Autowired
    public void setRepo(Repository repo) {
        this.repo = repo;
    }
}

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    public void doSomething() {
        userService.repo.save();
    }
}
medium
A. Field 'repo' in UserService is private and cannot be accessed directly
B. Missing @Autowired on UserService constructor
C. UserController should not use @Autowired on fields
D. Repository interface is not annotated with @Service

Solution

  1. Step 1: Check access to 'repo' field and identify cause of error

    The 'repo' field in UserService is private and cannot be accessed directly from UserController. Calling userService.repo.save() causes a compilation error due to private access.
  2. Final Answer:

    Field 'repo' in UserService is private and cannot be accessed directly -> Option A
  3. Quick Check:

    Private fields can't be accessed outside class [OK]
Hint: Private fields need getters; direct access causes error [OK]
Common Mistakes:
  • Assuming @Autowired must be on constructor only
  • Thinking field injection is disallowed in UserController
  • Confusing Repository annotation requirements
5. You want to inject two different implementations of an interface PaymentService into a controller using @Autowired. How can you specify which implementation to inject?
hard
A. Rename one implementation class to avoid conflict
B. Use @Autowired twice on the same field
C. Use @Qualifier annotation with the bean name along with @Autowired
D. Use @Autowired(required=false) to ignore one implementation

Solution

  1. Step 1: Understand multiple bean injection and use @Qualifier to specify bean

    When multiple beans implement the same interface, Spring needs help to know which one to inject. Adding @Qualifier with the bean name tells Spring exactly which implementation to use.
  2. Final Answer:

    Use @Qualifier annotation with the bean name along with @Autowired -> Option C
  3. Quick Check:

    @Qualifier + @Autowired = select specific bean [OK]
Hint: Use @Qualifier to pick the right bean when multiple exist [OK]
Common Mistakes:
  • Trying to use @Autowired twice on one field
  • Renaming classes doesn't solve injection ambiguity
  • Using required=false hides errors but doesn't select bean
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard