🤖

Spring Boot Autowiring

Jul 8, 2024

Spring Boot Autowiring

Overview

  • Dependency Injection in Spring Boot
  • Focus on Autowiring: Automating the connection of dependent objects

Example Scenario

  • Developers need a machine (laptop/desktop) to compile and debug code
  • Create a Laptop class with a compile method public void compile() { System.out.println("Compiling with 44 bugs"); }
  • Instantiate Laptop object in main class to call compile method
  • Issue: Direct instantiation using new keyword is not ideal

Spring Component and Autowiring

  • Use @Component to mark classes for Spring to manage and instantiate
  • Autowiring allows Spring Boot to automatically inject dependencies @Component public class Laptop { // methods }
  • Autowire with @Autowired to automatically wire dependencies @Autowired private Laptop laptop;
  • No need to manually create object instances

Types of Injection

  1. Field Injection
    • @Autowired on fields
    • Typically less preferred
  2. Constructor Injection
    • @Autowired on the constructor or omit since it's the default
    public Dev(@Autowired Laptop laptop) { this.laptop = laptop; }
  3. Setter Injection
    • @Autowired on setter methods
    @Autowired public void setLaptop(Laptop laptop) { this.laptop = laptop; }

Interface-based Autowiring

  • Create an interface Computer which Laptop and Desktop implement interface Computer { void compile(); }
  • Use Computer type for dependencies instead of specific Laptop/Desktop @Autowired private Computer computer;
  • Allows for loose coupling and flexibility in dependency types

Handling Multiple Implementations

  • If multiple beans of the same type exist, specify which one to use
  • Primary: Mark preferred bean with @Primary @Primary @Component public class Laptop implements Computer { // methods }
  • Qualifier: Specify the exact bean to use with @Qualifier @Autowired @Qualifier("laptop") private Computer computer;

Conclusion

  • Autowiring simplifies dependency management in Spring Boot
  • Understand different types of injection and when to use them
  • Managing multiple implementations using @Primary and @Qualifier

Additional Notes

  • Dependency injection helps in writing modular, maintainable code
  • Field injection is less preferred, Constructor and Setter injections are better
  • Always code to an interface for flexibility and loose coupling

Practical Tips

  • Use @Primary sparingly, only when dealing with multiple beans
  • Prefer Constructor injection for mandatory dependencies
  • Use @Qualifier for more specific bean resolution needs