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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With