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.