The @Autowired annotation

The @Autowired annotation injects object dependency implicitly. We can use the @Autowired annotation on a constructor-setter-and field-based dependency pattern. The @Autowired annotation indicates that auto wiring should be performed for this bean.

Let's look at an example of using the @Autowired annotation on a constructor-based dependency:

public class BankingService {  

private CustomerService customerService;

@Autowired
public BankingService(CustomerService customerService) {
this.customerService = customerService;
}
......
}

In the previous example, we have BankingService that has a dependency of CustomerService. Its constructor is annotated with @Autowired, indicating that Spring instantiates the BankingService bean using an annotated constructor and passes the CustomerService bean as a dependency of the BankingService bean.

Since Spring 4.3, the @Autowired annotation became optional on classes with a single constructor. In the preceding example, Spring would still inject an instance of the CustomerService class if you skipped the @Autowired annotation.

Let's look at an example of using the @Autowired annotation on a setter-based dependency:

public class BankingService {

private CustomerService customerService;

@Autowired
public void setCustomerService(CustomerService customerService) {
    this.customerService = customerService;
}
......
}

In the previous example, we saw that the setter method setCustomerService is annotated with the @Autowired annotation. Here, the annotation resolves the dependency by type. The @Autowire annotation can be used on any traditional setter method.

Let's look at an example of using the @Autowired annotation on a field-based dependency:

public class BankingService {

@Autowired
private CustomerService customerService;

}

As per the preceding example, we can see that the @Autowire annotation can be added on public and private properties as well. Spring uses the reflection API to inject the dependencies when added on the property, and that is the reason private properties can also be annotated. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset