In this quick article, we will discuss one important Spring interview question that is what Is the use of @Autowired annotation?
What Is the Use of @Autowired Annotation?
We can use the @Autowired to mark a dependency which Spring is going to resolve and inject. We can use this annotation with a constructor, setter, or field injection.
Constructor Injection:
@RestController
public class CustomerController {
private CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
}
Setter Injection:Field Injection:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
private CustomerService customerService;
@Autowired
public void setCustomerService(CustomerService customerService) {
this.customerService = customerService;
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
}
Learn more about @Autowired annotation at Spring @Autowired Annotation with Example
References
Spring @Autowired Annotation with Example
Interview Questions
Java
Spring Boot
Spring Framework
Comments
Post a Comment