Spring MVC 依赖注入在从 RequestMappingController 中调用的对象中不起作用
当我尝试执行如下操作并且 Spring MVC 中有一个 RequestMapping 控制器类实例化并调用外部类时,我无法在该类中使用依赖项注入,例如,如果我尝试使用,
@Resource(name = "savedsearchesService")
private SavedSearchesService savedsearchesService;
则会出现空指针异常。相反,我必须将 SavedSearchesService savingsearchesService
从我的控制器方法传递到另一个外部方法才能使其正常工作。
我想知道是否有人能指出为什么会这样,因为我很好奇,以及我是否遗漏了一些关于如何正确执行此操作的信息。谢谢
@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();
}
}
这是外部类的示例:
public class SomeExternalClass {
@Resource(name = "savedsearchesService")
private SavedSearchesService savedsearchesService;
public void Main () {
savedsearchesService.get();
}
}
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于这一行:
所有依赖于 springs 依赖注入的类都必须是 spring 管理的,而每当您使用 new 关键字实例化类时,情况并非如此。
有几种选择。提一下:
将
SomeExternalClass
注入您的控制器。创建一个隐藏实例化逻辑的 spring 管理工厂(例如
applicationContext.getBean()
)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
SomeExternalClass
into your controller.Create a spring-managed factory which hides instantiation logic (such as
applicationContext.getBean()
)