【问题标题】:Spring - Bean not accessible in filterSpring - 过滤器中无法访问 Bean
【发布时间】:2014-12-25 10:33:38
【问题描述】:

我正在开发 spring-mvc 应用程序。

我无法访问过滤器中的 bean。我遇到了异常

 org.springframework.beans.factory.NoSuchBeanDefinitionException : No qualifying bean of type [com.abc.app.SessionValue] is defined

我去 throw https://stackoverflow.com/a/11709272/3898076,但找不到问题。

我的 web.xml 中有以下条目

<servlet>
    <servlet-name>myapp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring_xyz-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

并且 spring_xyz-servlet.xml 包含组件扫描条目。

<context:component-scan base-package="com.abc.app" />
<context:annotation-config />
<context:spring-configured />

过滤代码:

WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(fConfig.getServletContext());
springContext.getBean(SessionValue.class);

这里面有配置问题吗?

谢谢。

【问题讨论】:

  • SessionValue 在哪里注册为 Spring bean?
  • 抱歉注册为使用注解的组件。
  • WebApplicationContextUtils 将检索根上下文,即由ContextLoaderListener 加载的上下文,它不会访问由DispatcherServlet 加载的上下文。将 bean 移动到根上下文。
  • 我还没有创建applicationContext.xml,我已经完成了spring_xyz-servlet.xml中的所有条目。所以在这种情况下,我是否必须创建 applicationContext.xml。或者我应该在 中定义 spring_xyz-servlet.xml 吗?
  • 您真的需要过滤器还是有其他方法可以实现您想要实现的目标?就像来自 Spring 的 HandlerInterceptor?还为ContextLoaderListener 定义相同的配置文件,因为这会复制所有的bean,通常不是你真正想要的。

标签: java spring spring-mvc filter


【解决方案1】:

如果没有其他约束,您应该尝试使用 Spring MVC Handler Interceptors,因为您在 Spring 上下文中,并且处理程序与过滤器几乎相似。

http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html

例子:

http://www.journaldev.com/2676/spring-mvc-interceptors-example-handlerinterceptor-and-handlerinterceptoradapter

【讨论】:

  • 是的,可以使用。但我也想使用过滤器运行。
  • 我更好地检查了你的错误,看起来你已经有了 Spring 上下文。你用组件注释你的 SessionValue。或者如果这是接口,您是否使用 Component 或 Service 注释了实现类?
  • 是的,@M.Deinum 指出了问题所在。只是在我的应用程序中找到解决方案。
猜你喜欢
  • 2011-01-25
  • 1970-01-01
  • 2013-10-26
  • 2014-09-24
  • 2015-04-30
  • 2018-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多