Spring Dependency Injection

Posted on Updated on

  • When writing a complex Java application, application classes should be as independent as possible of other Java classes to increase the possibility to reuse these classes and to test them independently of other classes while unit testing.
  • Dependency Injection (or sometime called wiring) helps in gluing these classes together and at the same time keeping them independent.
  • Let us understand this with an example

We have a controller class

You can inject your service and use the methods in your service class in any number of controllers

@Controller(“ExampleController”)
public class ExampleController extends BaseController{
@Autowired
//@Qualifier(“ExampleService”)
private ExampleService exampleService;
//here we are injecting the service in the controller wherein we can access the methods of that particular service in this controller now
@RequestMapping(value = “/getData.do”, method = {RequestMethod.GET,RequestMethod.POST})
public void getData(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
List usersList= (List) exampleService.getData(params);
//getData is the method in ExampleService.java
——————————-
—————
}

 

 

 

Leave a comment