When I try to do like below and I have a RequestMapping controller class within Spring MVC that instantiates and calls an external class, I am unable to use dependency injection within that class, such as if I try to use
@Resource(name = "savedsearchesService")
private SavedSearchesService savedsearchesService;
I get a nullpointer exception. Instead I have to pass SavedSearchesService savedsearchesService from my controller method into the other external method to get it to work.
I’m wondering if anyone can point out why it is this way as I am curious and if there is something I am missing as far as how to do this properly. Thanks
@Controller
@RequestMapping("")
public class MainController {
@Resource(name = "savedsearchesService")
private SavedSearchesService savedsearchesService;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String getPersons(Model model, HttpServletRequest request)
throws IOException {
HttpSession session = request.getSession();
SomeExternalClass someExternalClass = new SomeExternalClass ();
someExternalClass.Main();
}
}
Here is the example of the external classs:
public class SomeExternalClass {
@Resource(name = "savedsearchesService")
private SavedSearchesService savedsearchesService;
public void Main () {
savedsearchesService.get();
}
}
The problem is with this line:
All classes which depends on springs dependency injection must be spring managed, which is not the case whenever you instantiate classes with the new keyword.
There are several alternatives. To mention some:
Inject
SomeExternalClassinto your controller.Create a spring-managed factory which hides instantiation logic (such as
applicationContext.getBean())