简体   繁体   English

未将DispatcherServlet注入控制器

[英]DispatcherServlet not injected into the controller

I'm developing an application which is run both on Spring Boot (with no web.xml) and on WebSphere (with web.xml). 我正在开发一个可以在Spring Boot(没有web.xml)和WebSphere(有web.xml)上运行的应用程序。 There is a controller which needs to have DispatcherServlet injected into it. 有一个控制器需要将DispatcherServlet注入其中。 While it works on spring boot environment this fails on WebSphere - no bean of type DispatcherServlet can be found. 尽管它可以在Spring Boot环境中运行,但在WebSphere上却无法运行-找不到DispatcherServlet类型的bean。

Down in web.xml i use the parent context (Context Loader Listener) with middle-tier and several dispatchers having their separate contexts. 在web.xml中,我将父上下文(Context Loader Listener)与中间层和几个具有各自上下文的调度程序一起使用。 One of them contains such controller (among others). 其中之一包含此类控制器(以及其他)。

Why it's not working? 为什么不起作用? My first assumption is that Spring Boot first creates and registers the DispatcherServlet and then scans for controllers while when running with web.xml it happens in reversed order so Controllers are instantiated before DispatcherServlet is accessible from the context. 我的第一个假设是,Spring Boot首先创建并注册DispatcherServlet,然后在使用web.xml运行时扫描控制器,它以相反的顺序发生,因此在从上下文访问DispatcherServlet之前先实例化控制器。

How can I tackle this problem? 我该如何解决这个问题?

You can not inject DispatcherServlet directly because it is not registered in Spring Context (XmlWebApplicationContext for example). 您不能直接注入DispatcherServlet,因为它没有在Spring Context中注册(例如XmlWebApplicationContext)。 But you can extend DispatcherServlet, store link to itself to static field (in constuctor invocation). 但是您可以扩展DispatcherServlet,将自身的链接存储到静态字段(在构造函数调用中)。 And you this link anywhere in your code. 您可以在代码中的任何位置使用此链接。

Other way - if you create DispatcherServlet "manually" - you can register your DispatcherServlet as bean in application-context.xml. 另一种方法-如果您是“手动”创建DispatcherServlet的,则可以将DispatcherServlet作为bean注册到application-context.xml中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM