我将 spring mvc 应用程序配置从 xml 更改为代码。 自更改以来,我的拦截器中的所有注入(inject)属性都是 null (authenticationService)。
代码如下:
public class WebAuthenticationInterceptor extends HandlerInterceptorAdapter {
@Resource(type=WebAuthenticationService.class)
private IAuthenticationService authenticationService;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
if(authenticationService.authenticate(request).authenticated == false)
{
if(isAjax(request))
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
else
response.sendRedirect(String.format("%s/#/account/logout", request.getContextPath()));
return false;
}
return true;
}
public static boolean isAjax(HttpServletRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
}
拦截器配置:
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new WebAuthenticationInterceptor()).addPathPatterns("/home/**");
registry.addInterceptor(new MobileAuthenticationInterceptor()).addPathPatterns("/api/**");
}
你能说说我做错了什么吗?
谢谢
最佳答案
您正在使用 new
关键字创建对象。而是尝试在 Spring 配置中将 WebAuthenticationInterceptor
和 MobileAuthenticationInterceptor
定义为 @Bean
关于java - 如何在 Spring MVC 中向拦截器注入(inject)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17211916/