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 "so开发者_高级运维meView";
}
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.
Don't use getbean, that loses the purpose of doing DI. Use @Autowired instead. DI is meant to be used in a layered system like view, service, DAO, so that each layer is not depending on each other.
As a compliment to Pascal's post, Martin Fowler: Inversion of Control Containers and the Dependency Injection pattern is a must read.
And as cometta stated, that you should use @Autowire
annotation to achieve that. In addition to that, Spring supports name based and type based convention injections. I suggest you to read on that.
精彩评论