我尝试从过滤器中获取 spring web 应用程序上下文。
我之前是通过:
WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext())
没关系,因为我得到了所谓的 ROOT Web 应用程序上下文。 现在,我想像在 web.xml 中那样移动我所有的 spring 定义:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- Configure DispatcherServlet to use AnnotationConfigWebApplicationContext instead of default XmlWebApplicationContext. -->
<init-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</init-param>
<!-- Custom web configuration annotated class. -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>foo.bar.WebConfiguration</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
我从 web.xml 中删除了“旧”定义:
<!-- <context-param> -->
<!-- <param-name>contextConfigLocation</param-name> -->
<!-- <param-value>/WEB-INF/dispatcher-servlet.xml</param-value> -->
<!-- </context-param> -->
<!-- <listener> -->
<!-- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> -->
<!-- </listener> -->
现在,我没有更多的“ROOT”Web 应用程序上下文,过滤器无法获取另一个 Web 应用程序上下文。
我看到还有一个电话:
WebApplicationContextUtils.getWebApplicationContext(sc, attrName)
它允许将“属性”指定为第二个参数,它实际上是您想要的 Web 应用程序上下文。默认情况下,它是“org.springframework.web.context.WebApplicationContext.ROOT”。
我想我必须调用此方法,但我不知道将什么作为第二个参数。
PS:我也尝试使用 org.springframework.web.filter.DelegatingFilterProxy,但是 tomcat 抛出了他找不到经典(ROOT)Web 应用程序上下文的错误:
java.lang.IllegalStateException: No WebApplicationContext found: no ContextLoaderListener registered?
但是还有另一个上下文,它只是以另一种方式定义的。我不可能是唯一一个试图获得 ROOT 的另一个上下文的人。
感谢到目前为止的阅读。
最佳答案
我刚刚看了你的回答,是的,我昨天晚上就明白了 ;-) 我添加了 ROOT 上下文,这样定义它:
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>foo.bar.WebConfiguration</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
并且它的工作原理是,过滤器可以通过 Autowiring 直接访问服务。
我仍然觉得我的架构很脏,因为 ROOT 和“调度程序”上下文相同,我认为这不是一个好的做法。 也许我稍后会尝试将“WebConfiguration”一分为二。
还是谢谢你!
关于spring - 来自过滤器的 Servlet Web 应用程序上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29981261/