@Autowired Annotation in Spring

In spring, we can inject beans to an Object dependency with the help of the @Autowired Annotation.

Let’s see how it works in the below example.

package com.springexamples;

import org.springframework.beans.factory.annotation.Autowired;

public class Employee {
   private Designation designation;

   @Autowired
   public void setDesignation(Designation designation){
      this.designation = designation;
   }
   public Designation getDesignation( ) {
      return designation;
   }
}

If you see above, we use the @Autowired Annotation with the setter method. By doing this spring will inject the bean of the Designation Class to the designation property when it creates the bean for Employee class.

Kindly note that spring injects the class properties first while creating a bean of any class. Here while creating the bean for Employee Class, it will first create the bean for Designation Class and autowire it to the designation property.

We can use the @Autowired annotation with the property declaration as well instead of the setter method like below.

@Autowired
private Designation designation;

Kindly note that autowiring of the designation property would only be done if spring had created the bean of the Designation class and stored in IOC Container previously.

Spring will create the bean only if the bean definition is configured in the xml for Designation class or the designation class is annotated with any @Component annotation so that Spring using Component scanning creates the beans for such classes automatically.

@Component
Class Designation{
....
....
}

@Autowired annotation uses autowire byType internally when autowiring.