我将spring的mvc应用程序配置从xml更改为代码。 自更改以来,我的拦截器中的所有注入属性均为null(authenticationService)。如何在Spring MVC中将属性注入到拦截器中
的代码如下所示:
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'。 – dimchez
@dimchez将此添加为答案。 –
@TomG好吧,发表我的评论作为回答 – dimchez