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?
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
MyControllera Spring managed bean and injectMyServiceusing either setter or constructor based injection.And configure Spring to wire things together.