๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Spring @Autowired Annotation


Introduction

  • The @Autowired annotation in Spring is a powerful tool that simplifies dependency injection.
  • It is used for automatic dependency injection in Spring.

  • Advantages of @Autowired :
    • Reduces boilerplate code for dependency injection.
    • Enhances readability and maintainability.
    • Provides flexibility with @Qualifier, @Primary and collections.

  • How @Autowired Works ?
    • It uses reflection to identify a suitable bean for injection.
    • The Spring container scans for a bean matching the type of the field or parameter marked with @Autowired.

  • Placement of @Autowired :
    @Autowired annotation can be used with Constructors, Setter Methods & Fields to achieve particular injection which are explained as below:

    1. Constructor Injection:
      • Injects dependencies via the class constructor.
      • Example:
        @Autowired
        public Car(Engine engine) {
            this.engine = engine;
        }
      • It is the most preferred approach as it ensures immutability and simplifies testing.

    2. Setter Injection:
      • Injects dependencies via the setter method.
      • Example:
        @Autowired
        public void setEngine(Engine engine) {
            this.engine = engine;
        }

    3. Field Injection:
      • Injects directly into the field.
      • Example:
        @Autowired
        private Engine engine;
      • We should avoid Field Injection because it makes testing harder as it requires reflection-based mocking.

  • Click Here for @Autowired program used with constructor, setter methods and fields.

  • Scenarios for @Autowired :
    • Single Bean: @Autowired works properly if only one bean of the type exists. Also note that @Autowired annotation resolves dependencies by type.
    • Multiple Beans: If there are multiple beans of same type, then we have to use @Qualifier or @Primary for bean resolution. If we dont resolve this then it will throws a NoUniqueBeanDefinitionException exception
    • No Bean Found: If there is no bean found, then it will throws NoSuchBeanDefinitionException unless required = false is used.