在DelegatingFilterProxy上使用Spring和@Autowired [英] Spring and @Autowired on a DelegatingFilterProxy
问题描述
我正在尝试将Spring bean注入到过滤器中,但无法使其正常工作.
I'm trying to inject a spring bean into a filter, but can't make it work.
注入的bean始终为"null".我成功在Controllers和HandlerInterceptors中自动装配了相同的bean,因此已正确注释.
The bean injected is always "null". I succeed autowiring this same bean in Controllers and HandlerInterceptors so it's correctly annotated.
过滤器类位于其余Controllers的相同基本程序包中.
The filter class is under the same base-package of the rest of Controllers.
这是我的web.xml的相关部分
This is the relevant part of my web.xml
<filter>
<filter-name>CheckSession</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>CheckSession</filter-name>
<url-pattern>/panel/*</url-pattern>
</filter-mapping>
这是过滤器的代码
@Component
public class CheckSession extends OncePerRequestFilter implements Filter {
@Autowired private Usuario usuario;
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// always null
System.out.println("autowired " + usuario);
chain.doFilter(request, response);
}
}
过滤器在每个请求上触发.
The filter is triggering on every request.
这些是"Usuario" bean中的注释
These are the annotations in the "Usuario" bean
@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class Usuario implements java.io.Serializable { ... }
我想念什么?谢谢!
推荐答案
尝试为您的CheckSession bean明确定义名称,看看是否有帮助...像这样:
Try to explicitly define the name for your CheckSession bean and see if that helps... Like this:
@Component("CheckSession")
public class CheckSession extends OncePerRequestFilter implements Filter {
@Autowired private Usuario usuario;
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
// always null
System.out.println("autowired " + usuario);
chain.doFilter(request, response);
}
}
关键部分是这样:@Component("CheckSession")
The key part is this: @Component("CheckSession")
为了使事情更漂亮和更容易处理,我将 camelCase 的名称并将其重命名为"checkSession"(取消首字母大写).
And to make things prettier and easier to deal with down the road, I would camelCase the name and rename it to "checkSession" everywhere (de-capitalize first letter).
这篇关于在DelegatingFilterProxy上使用Spring和@Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!