Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an MVC application, where will the dependency injection take place?

When using Spring and Spring's MVC, where should the dependency injection (DI) take place?

Example, if you have a controller, and many actions in the controller.

Would you be doing:

@RequestMapping("/blah")
public String SomeAction()
{
    ApplicationContext ctx = new AnnotationConfigApplicationContext();
    MyService myService = ctx.getBean("myService");

    // do something here

    return "someView";
}

Would this be the best practice approach? Or is their a better way?

like image 668
mrblah Avatar asked Dec 13 '22 00:12

mrblah


1 Answers

The whole idea of Dependency Injection is to not have your classes know or care of how they get the objects they depend on. With injection, these dependencies should just "appear" without any request (hence the Inversion of Control). When using ApplicationContext#getBean(String), you're still asking for the dependency (a la Service Locator) and this is not Inversion of Control (even if this allows you to change the implementation easily).

So, instead, you should make your MyController a Spring managed bean and inject MyService using either setter or constructor based injection.

public class MyController {

    private MyService myService;

    public MyController(MyService aService) { // constructor based injection
        this.myService = aService;
    }

    public void setMyService(MySerice aService) { // setter based injection
        this.myService = aService;
    }

    @Autowired
    public void setMyService(MyService aService) { // autowired by Spring
        this.myService = aService;
    }

    @RequestMapping("/blah")
    public String someAction()
    {
        // do something here
        myService.foo();

        return "someView";
    }
}

And configure Spring to wire things together.

like image 198
Pascal Thivent Avatar answered May 24 '23 19:05

Pascal Thivent