The whole idea of โโInjection Dependency is not to let your classes know or care about how they get the objects they depend on. When injected, these dependencies should simply โappearโ without any request (hence the inversion of control). When using ApplicationContext#getBean(String) you are still requesting a dependency (a la Service Locator), and this is not an inverse of the control (even if this makes it easy to change the implementation).
So, instead, you should make MyController a Spring a managed bean and insert a MyService using either installation or constructor-based installation.
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 connect.
source share